How to unchecked a checkbox?
<input class=checked-val type="checkbox" value="foo" 开发者_如何学JAVAchecked="true" />
<input class=checked-val type="checkbox" value="bar" checked="true" />
Initially both checkbox are checked. But When I click any checkbox its checked value should be changed to checked=false. How can I do it using jquery or javascript?
You need to remove the attribute "checked".
$("#selector").removeAttr("checked");
Obviously the checkbox will check/uncheck anyway when a user clicks on it, but if you want to do it programatically:
<script type="text/javascript">
document.getElementById('cb_foo').checked = true;
document.getElementById('cb_bar').checked = true;
</script>
<input class=checked-val type="checkbox" id="cb_foo" value="foo" checked="true" />
<input class=checked-val type="checkbox" id="cb_bar" value="bar" checked="true" />
Use this:
$('.checked-val').removeAttr('checked');
Please note the syntax of your input must be:
<input type="checkbox" value="..." name="..." class="checked-val" checked="checked" />
The mechanic behind the check are:
- With
checked="checked"
, checkbox active and posted by the form submit - Without attribute
checked
, checkbox not selected and not posted by the form submit
Initially both checkbox are checked. But When I click any checkbox its checked value should be changed to checked=false. How can I do it using jquery or javascript?
If you want this to happen you can .one()
which attaches an event handler that only fires once. Combine that with the other items you can simply uncheck both boxes.
$(".checked-val").one("click", function(){
$(".checked-val").removeAttr("checked");
});
Code example on jsfiddle.
精彩评论