Reputation: 657
I have the following:
somefile.php
$("document").ready(function() {
var handler = function(data) {
var JsDiv = document.getElementById("somediv");
JsDiv.innerHTML = data;
};
$("input[type='checkbox']").change( function() {
console.log("execute lots of code in this function");
//I need to execute this part again with the new checkboxes
//.
//.
//.
//and then
$.ajax({
url: "ajaxFile.php",
success: function(data, textStatus, XMLHttpRequest) { handler(data); }
});
});
});
<div id="somediv">
<input type="checkbox" id="someid1" value="anything1" /> checkbox1
<input type="checkbox" id="someid2" value="anything2" /> checkbox2
</div>
ajaxFile.php
echo "
<input type='checkbox' id='someid3' value='anything3' /> checkbox3 <br />
<input type='checkbox' id='someid4' value='anything4' /> checkbox4
";
The problem is that $("input[type='checkbox']").change( function() {}) gets executed just fine when I first load the page, but once the new checkboxes have been loaded via ajax, they are not bounded to that function. I've seen things about bind() and live() but I don't quite get how to bind the new checkboxes to the function that I've already defined. I need to execute some code that is inside .change().. I would extract that code outside of .change() and call that function afterwards but I am not too sure how to do so.
If my question is not clear, please let me know and I will re-phrase. Thank you for your help.
Upvotes: 0
Views: 1702
Reputation: 10830
You just need to delegate to an ancestor listener that doesn't get destroyed. The below snippet uses .on()
with delegation syntax and is a replacement for your .change()
event listener.
$("#someContainer").on("change", "input[type='checkbox']", function() {
console.log("execute lots of code in this function");
});
someContainer
is obviously (I hope) a placeholder name. It just means any container wrapping around your target inputs. Do your best to identify the closest ancestor, as this will have the most performance benefits. But if you absolutely MUST, you could always use document:
$(document).on("change" /* .....etc.... */);
Upvotes: 4