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

2

9

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.

Aeroscope answered 1/4, 2012 at 14:53 Comment(5)
You choose a bad nickname. what will you do next year...?Auricular
I will change it to my real name after a few days only.Aeroscope
possible duplicate of Checkbox change event not firing ... please use the search before you ask a new question.Undertaker
@new to stackoverflow, adding a comment to every response asking for upvote isn't a good policy and won't get you more upvotes; asking a good question will. And your comments may get flagged.Edmundoedmunds
@FlomEnol Dear, sorry for that..bt that tym I could not even vote up answers. Thats because I did it. Now I hv removed any such cmnts. Sorry againAeroscope
L
11

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');        
});
Lodie answered 1/4, 2012 at 14:55 Comment(0)
L
1

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();
Llano answered 1/4, 2012 at 14:55 Comment(1)
Thanks @Llano I like 2nd method u describe.Aeroscope

© 2022 - 2024 — McMap. All rights reserved.