How to make change event work for radiobutton for html added with replaceWith

I managed to get the change event firing for a radiobutton. However I now needed it to work for html where the radiobutton is added to the markup with replaceWith.

So it is added to my markup with:

$(this).replaceWith('<input type="radio" name="variety" value="null" id="myradio" />');

So, the code I have for catching the change event is:

$('#myradio').change(function () {
        alert("Hello");
    });

So does anyone know how I would make this work given the radio button is now added to the page after the initial page load?

Answers


You could use .on() (jQuery 1.7+) or .delegate() (jQuery 1.4.3+) to subscribe to the change event in order to account for dynamically added elements.

For example:

$('#myradio').live('change', handler);                // jQuery 1.3+

$(document).delegate('#myradio', 'change', handler);  // jQuery 1.4.3+

$(document).on('change', '#myradio', handler);        // jQuery 1.7+

It's also important to point out that it is not necessary to place this subscription inside a document.ready callback.


You could use the following:

$('body').on('change', '#myradio', function () {
    alert("Hello");
});

If you know beforehand the element in which you'll be putting the radiobutton, you should change the 'body' selector to match that element for performance.


either:

  • use jQuery on to a parent

    <div id="container">
        <!--replaceable elements-->
    </div>
    
    //this will take effect on current and future children
    $('#container').on('change','targetSelector',function(){
        alert("Hello");
    });
    
  • or bind directly to the new element

    function func(){
        alert("Hello");
    }
    
    var newEl = $('<input type="radio" name="variety" value="null" id="myradiobutton" />');
    newEl.change(func);
    $(this).replaceWith(newEl);
    

i prefer the first one though, for performance and clean code.


You could create the radio button, add the change event, then replace this with the radio button.

var $radio = $('<input type="radio" name="variety" value="null" id="myradio" />');
$radio.change(function () {
    alert("Hello");
});
$(this).replaceWith($radio);

Need Your Help

Clion memory view

c++ memory clion

I can't find a memory view in Jetbrain's clion IDE.

Use REST in Spring without MVC

java rest spring-mvc

I want to use REST in Spring without using MVC framework, but it seems they encourage using it with controllers only!