I have an EJS page that is using AJAX to retrieve some data. after loading the data, I want to append certain content to a div. In the appended content, there are checkboxes that uses the following script:
<script>
$('#selectall').change(function () {
$('.checkbox').prop('checked', this.checked).trigger('change');
});
</script>
Here is my ajax:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/mytableajax',
success: function(result) {
//result is printed, everything is retrieved correctly
$('#mytable').empty();
var eventresult = JSON.parse(result);
var node = document.getElementById('mytable');
toAppend += '<input type="checkbox" id="selectall" class="c-check">'; //This checkbox will allow me to select all other checkboxes
//I have other checkboxes appended at the bottom with the class "checkbox"
node.innerHTML = toAppend;
document.getElementById('mytable').appendChild(node);
})
When i first access the page, the select all function works. However, when the data is being changed using AJAX as shown in the above code, the select all function stop working. I figured that my script seems to be unable to execute within the 'success' callback of AJAX, as all my functions that uses script seem to fail after changing/appending using AJAX.
Is there any way to execute scripts within my AJAX 'success' callback? Appreciate any feedback/advice!
I found a solution that actually works, hope it helps someone with the same issue.
$(document).on('change', '#selectall' , function() {
$(".checkbox").attr('checked', $(this).is(":checked")).trigger('change');
});
Basically, using the .on method in this format instead of .change method allows the content from AJAX to access this script.
Got the idea from here: https://forum.jquery.com/topic/use-on-click-do-not-work-after-ajax-call
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.