Hi stackoverflow community
I'm trying to work with an on change event of radio buttons created dynamically from ajax call. This buttons are created based on mysql result and every radio button should listen to an on change event.
Here is my ajax call:
$.ajax({
...
success:function(ajax_result){
ajax_result.forEach(fn_Populate); // could be replaced with for loop
function fn_Populate(element){
$("xdiv").append("<input type='radio' id='radio_" element[0] "' name='xradio'>");
$("xdiv").append("<label for='radio_" element[0] "'>" element[0] "</label>");
}
}
});
This should create n radio buttons according to ajax result, example radio_1, radio_2, radio3, all with name xradio.
After radio button are created I need to identify when a button is clicked. Here is the code in jquery:
$("input[type=radio][name=xradio]").change(function(){
alert("DO SOMETHING");
// rest of code
});
The problem is that change event is not fired if is outside the ajax call.
I need to fire it outside the ajax call because it will generate another dynamic buttons thru a new ajax call.
All help will be appreciated.
Thanks
CodePudding user response:
Consider the following.
$("#xdiv").on("change", "input[name=xradio]", function(event){
console.log("Change on " $(this).attr("id"));
});
This is using delegation to bind the event callback to a static element that is the parent of the dynamic element. The delegation allows it to be triggered by the child element.
See More: https://api.jquery.com/on/