How to check and uncheck a checkbox with jQuery

Example form

Our example form looks like this:

<input type="checkbox" name="foo" value="bar" />
<input type="button" οnclick="show_checked()" value="Show" />
<input type="button" οnclick="set_checked(true)" value="On" />
<input type="button" οnclick="set_checked(false)" value="Off" />

There's checkbox with name "foo" and then three buttons. The first calls a functionto show us if the checkbox is checked or not, and the second two change it from being checked to not being checked.

Check if the checkbox is checked

There are several ways to get to work out if a checkbox is checked or not with jQuery, and here a couple of alternatives. Each will return true if it's checked or false if it's not.

$('input[name=foo]').is(':checked')
$('input[name=foo]').attr('checked')

Set the checkbox to checked or not checked

The status of the checkbox can be changed using the attr() function like so, to check the box:

$('input[name=foo]').attr('checked', true);

and like so to uncheck the box:

$('input[name=foo]').attr('checked', false);

Working example

And finally, here's the example form in action:

     

A note about boolean values

There is a discussion in the comments below about issues found with Chromium which may be related to string values of true and false being passed whereas it needs to be strictly a boolean true or false otherwise unexpected consequences can happen.

It has been suggested to use .removeAttr() instead but this may have other consequences from my reading of the comments on the jQuery documentation page for the function. I will follow up this post at a later date and do more testing to confirm for sure

Toggling a checkbox when clicking a label

Note that Javascript is not required to toggle a checkbox when clicking some text; that's what HTML <label>s are for. Have a read of my follow up post using HTML <label> to toggle and select fields for more information.

转载地址:http://www.electrictoolbox.com/check-uncheck-checkbox-jquery/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值