I have a JavaScript function that listens for a change on a Radio button
in order to execute the next batch of code. However, I find that when I physically click the button, it's different from setting it in code (through .prop("checked",true);
). Why when I change which radio button is selected through .prop()
does it not trigger the event handler .change()
? How can I adjust my code so that the handler hears the change?
Here's a JSFiddle that demonstrates the problem
Click the Radio buttons
and the value will appear in a div
below. However, when you click the "change to blue" button it will reset the Radio button
to the "blue" option but the value will not be updated in the "output" div.
HTML:
<div id='colors'>
<input type="radio" id="black" value="Black" name="myRadio" /><label for="black">Black</label><br>
<input type="radio" id="blue" value="Blue" name="myRadio"/><label for="blue">Blue</label><br>
<input type="radio" id="green" value="Green" name="myRadio"/><label for="green">Green</label>
</div>
JS:
$('#changeRadio').click(function(){
$("input:radio[id='blue']").prop("checked",true);
});
$('#colors input').change(function(){
var selected_item = $(this).val()
$('#output').html(selected_item);
});
You are just changing the state of the Checkbox
and not trigger an event on the object; you need to do something that triggers event and changes the state at the same time.
Change:
$("input:radio[id='blue']").prop("checked",true);
To:
$("input:radio[id='blue']").trigger('click');
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments