Bineesh Bineesh - 6 months ago 20
Javascript Question

How to select a table element and run javascript

I have a table and want to run js on click event of a button in the row (populated by datatables) i used the code from datatables website but seems not working.



$(document).ready(function(){
$('#expvisa').on('click','button',function() {
var msData = table.row($(this).parents('tr')).data();
alert( msData[0] +" salary is: "+ msData[4]);
});
});

<table id="expvisa" class="table table-bordered" cellspacing="0" >
<thead>
<tr>
<th>EMP Id</th>
<th>VISA OFFICE</th>
<th>EMPLOYEE NAME</th>
<th>QATAR ID</th>
<th>ID MONTH</th>
<th>Process </th>
</tr>
</thead>
</table>





This is the script creating the table.



function bringvisa_exp(){

$.ajax({
url:"report_visaexp.php",
type:"POST",
data:{comp_n:$('#comp_n').val(),visam_f:$('#visam_f').val()},
async: false,
success: function(dataX){
obj = JSON.parse(dataX);
$('#expvisa').DataTable({
data: obj,
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Apply</button>"
} ]
} );
}
});
}




enter image description here

Answer

You need to call this script inside ajax call success function block. Because your click event is bind before DOM is ready.

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

Update your bringvisa_exp() function with following:

function bringvisa_exp(){       
        $.ajax({                
            url:"report_visaexp.php",
            type:"POST",
            data:{comp_n:$('#comp_n').val(),visam_f:$('#visam_f').val()},
            async: false,
            success: function(dataX){   
                obj = JSON.parse(dataX);
                $('#expvisa').DataTable({
                  data: obj,
                  "columnDefs": [ {
                    "targets": -1,
                    "data": null,
                    "defaultContent": "<button>Apply</button>"
                   } ]
                } );
                $('#expvisa').on('click','button',function() {
                  var msData = table.row($(this).parents('tr')).data();
                  alert( msData[0] +" salary is: "+ msData[4]);
                });
            }                               
        }); 
    }
Comments