I have an HTML checkbox element on my page like so:
<input type="checkbox" id="locked" /><label for="locked">Locked</label>
And I make a call inside my $(document).ready() to change this to be a jQuery UI checkbox button like so:
$('#locked').button({
'icons': {
'primary': 'ui-icon-unlocked'
},
'label': 'Unlocked'
});
Background context being that the user can use this button to lock/unlock a particular entity s开发者_StackOverflow中文版o that a background process will not alter it and it starts with an 'Unlocked' status. If javascript is not turned on, the user sees a checkbox and the label 'Locked' next to it.
I want to be able to programmatically check/uncheck this checkbox button. I've tried:
$('#locked').attr('checked', false);
But the checkbox button does not update to reflect the underlying control's checked status.
I could test the checkbox's checked property then do a .click() if it doesn't match what I want but that doesn't sound very elegant.
Try this one:
$('#locked').removeAttr('checked');
It's just a guess to your case, but usually works for me like a charm.
EDIT: Taking a look at jQueryUI documentation, here is a method you should also try after changing programatically the state of the checkbox:
$('#locked').button( "refresh" )
"Refreshes the visual state of the button. Useful for updating button state after the native element's checked or disabled state is changed programatically."
jQuery 1.5.x and earlier: $('#locked').attr('checked','');
jQuery 1.6.0 and later: $('#locked').prop('checked', false);
The checked
attribute is considered a property, and has its own method now. You should use .prop()
if it's available to ensure the desired behavior is observed by your users.
Use the new .prop() function in jQuery 1.6+:
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
or with id
$('#myCheckboxId').prop('checked', false);
For jQuery 1.5 and below
$('.myCheckbox').attr('checked','checked');
$('.myCheckbox').removeAttr('checked');
In newer versions of JQueryUI the checkboxradio()
function must be used with the refresh
option like so:
$("#selector").checkboxradio("refresh");
in order to update the checkbox visually after .prop("checked", true);
or .prop("checked", false);
has been used to check or uncheck the checkbox itself.
Source: The API documentation: http://api.jqueryui.com/checkboxradio/
refresh()
Refreshes the visual state of the widget. Useful for updating after the native element's checked or disabled state is changed programmatically.
精彩评论