call change() event handler if I select radio button programatically

shashwat picture shashwat · Apr 1, 2012 · Viewed 8.8k times · Source

I have HTML like this:

<input type="radio" name="type" value="FL" checked="checked" />Fixed
<input type="radio" name="type" value="SV" />Saving
<input type="radio" name="type" value="L2" />Type 2

And following script

$(function () {
        $('input[name=type]').change(function () {
            alert($(this).val());
        });
        $('input[value=SV]').attr('checked', 'checked');
    });

Firstly, have added a change event to radio button. change event handler triggered if I am selecting radio button from UI. But it does not triggered when I change selected radio button value pro-grammatically.

I want change event also to be triggered when I select radio button pro-grammatically.

Answer

Rory McCrossan picture Rory McCrossan · Apr 1, 2012

You can use trigger() to programmatically raise an event:

$(function () {
  $('input[name="type"]').change(function() {
    console.log($(this).val());
  });
  $('input[value="SV"]').prop('checked', true).trigger('change');        
});