SNag
SNag

Reputation: 18151

Radio button change event not firing when radio is selected programmatically

In the following code, clicking the selectRadio2 button does not fire the radio change event! Why not? Is there a workaround?

HTML:

<input id="radio1" type="radio" name="radioGroup" value="One"/>
<label for="radio1">One</label><br/>
<input id="radio2" type="radio" name="radioGroup" value="Two"/>
<label for="radio2">Two</label><br/>
<input id="radio3" type="radio" name="radioGroup" value="Three"/>
<label for="radio3">Three</label>

<br/><br/>
<button id="selectradio2">Select Radio 2</button>

JS:

$("input[name=radioGroup][type=radio]").change(function() {
    alert($(this).attr("id") + " checked");
});

$("#selectradio2").click(function() {
    $("#radio2").prop('checked',true);
});

JSFIDDLE DEMO

Upvotes: 9

Views: 9079

Answers (1)

Felix
Felix

Reputation: 38112

Since the change event requires an actual browser event initiated by the user instead of via javascript code. You need to trigger the change event using:

$("#selectradio2").click(function() {
    $("#radio2").prop('checked',true).change(); // or trigger('change')
});

Updated Fiddle

Upvotes: 24

Related Questions