jQuery UI radio button - how to correctly switch checked state
Solution 1:
You need to call the refresh
method after changing the underlying state:
Refreshes the visual state of the button. Useful for updating button state after the native element's checked or disabled state is changed programatically.
Working example: http://jsbin.com/udowo3
function setRadio(id) {
var radio = $('#' + id);
radio[0].checked = true;
radio.button("refresh");
}
That uses IDs for the radios, but it doesn't matter as long as you get a jQuery instance containing the relevant input[type=radio]
element.
Solution 2:
Despite posts to the contrary, you CAN reference a radio button by ID. Not sure why JQuery UI doesn't refresh the buttons automatically when checked, but you do it like this:
$('selector').attr('checked','checked').button("refresh");
Working example:
<div id = "buttons">
<label for="b1">button1</label>
<label for="b2">button2</label>
<label for="b3">button3</label>
<input type="radio" name = "groupa" id = "b1" value="b1">
<input type="radio" name = "groupa" id = "b2" value="b2">
<input type="radio" name = "groupa" id = "b3" value="b3">
</div>
<script>
$('#buttons input').button();
$('#b3').prop('checked', true).button("refresh");
</script>
Solution 3:
If someone is still getting this issue, make use of:
.prop('checked',true);
instead of:
.attr("checked", true);
Solution 4:
Looking at the code, you need to toggle the ui-state-active
class, but the simplest way is probably just $('someradiobutton').trigger('click')
(or if you don't want your custom event handlers to run, $('someradiobutton').trigger('click.button')
).