Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 847
shashwat Avatar asked Apr 01 '12 14:04

shashwat


2 Answers

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');        
});
like image 99
Rory McCrossan Avatar answered Oct 21 '22 08:10

Rory McCrossan


It won't change automatically. You have to do one of the following:

either

$('input[value=SV]').attr('checked', 'checked').trigger("change")

or

$('input[value=SV]').attr('checked', 'checked').change();
like image 20
FreeCandies Avatar answered Oct 21 '22 08:10

FreeCandies