Testing if a checkbox is checked with jQuery
If the checkbox is checked, then I only need to get the value as 1; otherwise, I need to get it as 0. How do I do this using jQuery?
$("#ans").val()
will always give me one right in this case:
<input type="checkbox" id="ans" value="1" />
Use .is(':checked')
to determine whether or not it's checked, and then set your value accordingly.
More information here.
$("#ans").attr('checked')
will tell you if it's checked. You can also use a second parameter true/false to check/uncheck the checkbox.
$("#ans").attr('checked', true);
Per comment, use prop
instead of attr
when available. Eg:
$("#ans").prop('checked')
Just use $(selector).is(':checked')
It returns a boolean value.
链接地址: http://www.djcxy.com/p/9582.html上一篇: 对一组复选框使用HTML5“required”属性?
下一篇: 测试复选框是否使用jQuery进行检查