Reputation: 667
I am trying to insert buttons into the JQuery DataTables but it seems that when the button is pressed, nothing happen.
The code as follows (for the JQuery Datatable):
var oTable = $('#example').dataTable( {
"aaData": movieclips,
"bProcessing": true,
"bAutoWidth": false,
"fnInitComplete": function() {
var oSettings = this.fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("tfoot input")[i].value = oSettings.aoPreSearchCols[i].sSearch;
$("tfoot input")[i].className = "";
}
}
},
"aoColumns": [
{
"sTitle": "Title",
"sClass": "center",
"sWidth": "80%"
},
{
"sTitle": "Video URL",
"sClass": "center",
"fnRender": function(obj) {
var sReturn = obj.aData[ obj.iDataColumn ];
var returnButton = "<input class='approveButton' type='button' name='" + sReturn + "' value='Play'></input>";
return returnButton;
},
"sWidth": "20%"
}
]
} );
The approveButton function as follows:
$(".approveButton").click(function() {
alert(this.name);
try {
alert(this.name);
} finally {
return false;
}
}
Any Insight?
Upvotes: 11
Views: 7294
Reputation: 76880
If you use jquery < 1.7 you should use delegate() or live()
$(".approveButton").live('click', function() {
alert(this.name);
try {
alert(this.name);
} finally {
return false;
}
}
$("body").delegate(".approveButton", "click", function() {
alert(this.name);
try {
alert(this.name);
} finally {
return false;
}
}
otherwise use on() as suggested by nnnnnn
Upvotes: 3
Reputation: 150030
If you assign the handler with $(".approveButton").click(...)
it will only apply to elements that already exist which match the ".approveButton"
selector at that moment. That is, elements created later will not automatically get handlers of their own. I'm assuming that that is the problem - if not you can disregard the following...
Fortunately there is a mechanism for creating a handler that will automatically work on matching elements that are created in the future:
$(document).on("click", ".approveButton", function() {
// your function code here
});
Notice that the initial selector is document
- this will work, but you should set it up on a parent element closer to your buttons if you can, so perhaps the following:
$("#example").on("click", ".approveButton", function() { /* your code */ });
(I'm not sure if "#example" is the most appropriate parent for this purpose, but you don't show any of your HTML, so...)
Have a look at the jQuery doco for .on()
for more information.
Or, if you're using a version of jQuery older than 1.7 you can use `.delegate()'
Upvotes: 8