I have an table which initial filled server sided with 300 rows or it can be even more.
var strhtml = '<table id="table" class="">';
strhtml += '<tbody>';
strhtml += '<tr>';
strhtml += '<td><input type="checkbox" class="select" id="select_' + result.data[i].cmid + '" name="select_' + result.data[i].cmid + '" value="' + result.data[i].cmid + '"' + checked + '/></td>';
strhtml += '<td><input ...
strhtml += '<td><input type="text" class="update" id="shnr_' + result.data[i].cmid + '" name="shnr_' + result.data[i].cmid + '" value="' + shirtnr + '" /></td>';
strhtml += '<td>' + result.data[i].posc + '</td>'; strhtml += '</tr>';
strhtml += ' </tbody>'
strhtml += '</table>';
I have an event selector for the class="update":
jQuery('.update').on('change',function () {
var arrelement = jQuery(this).attr('id').split('_');
var objCheckbox = jQuery("#select_" + arrelement[1]);
if (jQuery(objCheckbox).is(':checked'))
checkSelected(objCheckbox);
});
This initial is al working fine.
But after the AJAX call the event selector is not working anymore and I understand a bit why, because the table is completely build again with jQuery now, which means the DOM has been changed and the 'change' event is not bind anymore to elements as the page was opened.
But how do you resolve this. I read some about 'delegation' and I can't visualize so that I can imagine what is happening.
One thing what I have done is add the event selector again to the .done of the AJAX call. Than it is 'working' but is this the idea behind 'delegation'? I think not, that it run to the complete document and bind the event selector...?
jQuery.ajax({
type: "POST",
dataType: "json",
url: getUrl,
data: {task: "Filter", view: "viewname", format: "json", arfilter: arfilter},
success: function(result, status, xhr) {displayFilterResults(result); },
error: function() { console.log('ajax call failed'); },
})
.done(function() {
jQuery('.update').on('change',function () {
var arrelement = jQuery(this).attr('id').split('_');
var objCheckbox = jQuery("#select_" + arrelement[1]);
if (jQuery(objCheckbox).is(':checked'))
checkSelected(objCheckbox);
});
});
But this looks very strange to me. Now I have implemented twice the event selector 'change' for the class="update", once the 'normal' way and what I expect, and the second time which will be used after an AJAX call.
I should more expect that in the .done something will be done to reorganize the DOM and add the event selector to elements and that everything is working via the 'normal' event selector.
Can someone help me a bit how this should be done?
Nico