HTML radio buttons created at runtime fire change first time only

I create at runtime a set of radio buttons nested within their labels.

Then I associate an on change event: it gets fired at the first change only: if I click those radio button a second time, it doesn't - even if in the meantime I clicked a different radio button.

I am using jQuery 3.x, Bootstrap 3.3.7, and running on latest Chrome on OSX

Where should I start investigating from?

Answers 1

  • You must bind the event-listener to the radio button itself when the element changed the event is no longer listening by the element.

    A solution for this issue is to use a delegate. Checkout the doc below since you are using jQuery,

    http://api.jquery.com/delegate/

    $( "table" ).on( "click", "td", function() {
      $( this ).toggleClass( "chosen" );
    });
    

    In simple term, delegate binds the event to the parent (not necessary the direct one) and when the target element (either existing element at document ready OR dynamic generated element at runtime) get clicked the event get bubble up. Your delegate (table in the sample code above) will catch the event and perform certain task(s).


Related Articles