0

I am using jQuery bind on bunch of radio buttons with the following code:

jQuery().ready(function() {
    jQuery("input[name='rank_number']:radio").bind('change', function(){

        submitSelectedRank();
    });

});

This code is working fine on initial load of the page but the HTML for these radio buttons can be reloaded via an Ajax call using:

$.ajax({
        type: "POST",
        url: "/loadMyRadioButtons",
        data: rankings,
        dataType: "html",
        success: function(response)
        { 
            $('#radioBtnDiv').html(response);
        }
    });

Now the issue, anytime this ajax call replaces the HTML code, the binding stops working. How do I fix that?

user1195192
  • 679
  • 3
  • 11
  • 19

1 Answers1

3

Use event delegation:

$(document).on('change', "input[name='rank_number']:radio", function(){
    submitSelectedRank();
});

Here, document can be replaced by any parent of your inputs that exists on page load. i.e:

$('#radioBtnDiv').on('change', "input[name='rank_number']:radio", function(){
    submitSelectedRank();
});
blex
  • 24,941
  • 5
  • 39
  • 72
  • @user1195192 Any errors in your console? (F12). It should work: http://jsfiddle.net/ke3ek75j/ – blex Jul 16 '15 at 17:01
  • @user1195192 Sure, create a [Pastebin](http://pastebin.com/) – blex Jul 16 '15 at 17:07
  • pastebin.com/embed_iframe.php?i=t7yY4pYu – user1195192 Jul 16 '15 at 17:40
  • @user1195192 I can see that `#radioBtnDiv` exists, but it's not enough to tell what's wrong. Could you show the code you get once the radio buttons are in place? By doing [this](http://i.imgur.com/fkLOd7D.png). – blex Jul 16 '15 at 17:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/83468/discussion-between-blex-and-user1195192). – blex Jul 16 '15 at 18:16