0

Hi stackoverflow community

I'm trying to work with the on change event of radio buttons that are created dynamically from an ajax call. These radios are created based on a MySQL result and each radio button should listen to an onChange 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 the radio buttons according to the ajax result, example radio_1, radio_2, radio_3, all with name xradio.

After the radio buttons 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 the change event is not fired if it is outside of the ajax call.

I need to fire it outside of the ajax call because it will generate another dynamic button through a new ajax call.

All help will be appreciated.

Thanks

Jack
  • 220
  • 1
  • 8
Hugo
  • 3
  • 2

1 Answers1

1

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/

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Why answer a question that has been asked & answered many times before instead of voting to close as a duplicate? – devlin carnate Jun 07 '22 at 17:09
  • @devlincarnate your close vote does properly address OP's question. This simply presents an answer to OP with a real world example based on his specific code. If others feel the same as you, they will vote to close as well. – Twisty Jun 07 '22 at 17:11
  • @devlincarnate I did a research before asking my question and didn't find a right answer. Looking to Twisty code I found that I was missing a parameter not listed in similar questions. As Twisty wrote, I'm using my own real example and it's kindly appreciate people can help. – Hugo Jun 07 '22 at 17:23