Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio button change event not firing when radio is selected programmatically

Tags:

jquery

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

like image 362
SNag Avatar asked Apr 16 '14 12:04

SNag


People also ask

Does radio button have Onchange?

As you can see here: http://www.w3schools.com/jsref/event_onchange.asp The onchange attribute is not supported for radio buttons. The first SO question linked by you gives you the answer: Use the onclick event instead and check the radio button state inside of the function it triggers.

How do you check radio button is selected or not?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

Which event handler is called when a radio button is selected?

To define the click event handler for a button, add the android:onClick attribute to the <RadioButton> element in your XML layout.25-Aug-2022.


1 Answers

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

like image 147
Felix Avatar answered Oct 06 '22 12:10

Felix