Get the value of a cell using button click.

Get the value of a cell using button click.

GlyndwrGlyndwr Posts: 128Questions: 35Answers: 1

I am trying to get the value of a cell (currently hidden) on button click. I copied the example; however I can not get the value.

   $('#activityTable tbody').on( 'click', 'button', function () {
    alert("activityTable");
    var data = table.row( $(this).parents('tr') ).data();
    alert( "The ID is: "+ data[ 0 ] );
} );

The first alert displays, then the screen refreshes and the second alert is not displayed. There is no error in the console. I have tried moving the .on( 'click', 'button', function () outside of the .ready(function() and the same thing occurs.

The full js is:

    $(document).ready(function(){
        $("#includedContent").load("Menu.html");

        $('[data-toggle="tooltip"]').tooltip();

    $('#ajaxGetUserServletResponse1').text('');

        if ( $.fn.dataTable.isDataTable( '#activityTable' ) ) {
            var activityTable = $('#activityTable').DataTable();
        }
        else {
            var activityTable = $('#activityTable').DataTable( {

                "info":     false,
                dom: 'Bfrtip',
                buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
                columns: [
                          {data: 'hrId',
                              visible: false,
                              searchable: false},
                          {data: 'hrStartDate'},
                          {data: 'hrEndDate'},
                          {data: 'hrLocation'},
                          {data: 'hrType'},
                          {data: 'hrActualKM'},
                          {data: 'hrOffset'},
                          {data: 'hrKilometres'},
                          {data: 'hrNightsUnderCanvas'},
                          {
                              data: null,
                              className: "center",
                              defaultContent: '<button>Click!</button>'
                          }
                         ],

                 "footerCallback": function ( row, data, start, end, display ) {
                     var api = this.api(), data;

                     // Remove the formatting to get integer data for summation
                     var intVal = function ( i ) {
                         return typeof i === 'string' ?
                             i.replace(/[\$,]/g, '')*1 :
                             typeof i === 'number' ?
                                 i : 0;
                     };

                     // Total over all pages for KM
                     totalKM = api
                         .column( 7 )
                         .data()
                         .reduce( function (a, b) {
                             return intVal(a) + intVal(b);
                         }, 0 );

                     // Total over all pages for NUC
                     totalNUC = api
                         .column( 8 )
                         .data()
                         .reduce( function (a, b) {
                             return intVal(a) + intVal(b);
                         }, 0 );

                     // Update footer
                     $( api.column( 7 ).footer() ).html(
                             totalKM
                     );
                     $( api.column( 8 ).footer() ).html(
                             totalNUC
                     );
                 },

            } );
        }


        //Get Hike List
        $.ajax({
            url : 'HikeListView', // Your Servlet mapping or JSP(not suggested)
            data : {
                ssYMID : sessionStorage.getItem('ssYMID'),
            }, 
            type : 'POST',
        })
        .fail (function(jqXHR, textStatus, errorThrown) {
    //      alert(jqXHR.responseText);
            if(jqXHR.responseText.includes('No Hikes')){
                $('#ajaxGetUserServletResponse1').text('No Hikes.');
            }else{
                $('#ajaxGetUserServletResponse1').text('Error getting Hikes.');
            }
            $("#startDate").focus();
        })
        .done(function(responseJson1a){
            // JSON response to populate the activities table
            dataType: "json";

            activityTable.clear();
            activityTable.rows.add(responseJson1a).draw();
        })

        $('#activityTable tbody').on( 'click', 'button', function () {
            alert("activityTable");
            var data = table.row( $(this).parents('tr') ).data();
            alert( "The ID is: "+ data[ 0 ] );
        } );

    }); // end document.ready

Answers

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954

    I think the problem is you are using columns.data which means Datatables is using objects. But in your click event you are trying to access the data with data[0] which is trying to access array based data.

    Change line 104 to this and it should work:

    alert( "The ID is: "+ data.hrId );
    

    Kevin

  • GlyndwrGlyndwr Posts: 128Questions: 35Answers: 1

    Hi Kevin,

    I tried this and no change to the result. So I added "alert("here");" after the var line which showed the var line is failing (the alert did not display). So I commented out the var line and added"

    alert("here");
    alert("The ID is: " + this.hrId);
    

    The second display is "The ID is: undefined". So you are correct it is around extracting the data; somehow. Now to work out how :-)

    Kind regards,

    Glyn

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954

    Your basic code works here:
    http://live.datatables.net/dovidobi/1/edit

    One change I made was removing tbody from $('#activityTable tbody').on( 'click' in line 101. Removed it because my example doesn't have a tbody until after Datatables is built. Might help you to remove it.

    Kevin

  • GlyndwrGlyndwr Posts: 128Questions: 35Answers: 1

    Thank you Kevin; however no joy.

    Kind regards,

    Glyn

  • GlyndwrGlyndwr Posts: 128Questions: 35Answers: 1

    Hi Kevin,

    The answer is in: https://datatables.net/forums/discussion/36563/var-data-table-row-this-closest-tr-data-does-not-return-any-data

    Change:

     var data = table.row( $(this).parents('tr') ).data();
    

    To:

     var data = activityTable.row( $(this).parents('tr') ).data();
    

    Giving:

    $('#activityTable').on( 'click', 'button', function () {
        alert("activityTable");
        var data = activityTable.row( $(this).parents('tr') ).data();
        alert("here");
        alert( "The ID is: "+ data.hrId );
    } );
    

    Isn't it always obvious when you know the answer :-)

    Thanks for your help; greatly appreciated.

    Kind regards,

    Glyn

This discussion has been closed.