jQuery jquery中的复选框验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13239973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checkbox validation in jquery
提问by Wojtek
I need help in the selection checkbox on the form. I would like to display an alert as a form checkbox is unchecked (only). My code:
我需要表单上选择复选框的帮助。我想在表单复选框未选中(仅)时显示警报。我的代码:
<form action="index.php?page=contact&send=ok" method="POST" id="form">
[...]
<label for="message">Checkbox:</label><input type="checkbox" id="checkbox" name="checkbox">
<input type="submit" value="Send" onclick="testcheck()" />
</form>
<script type="text/javascript">
function testcheck()
{
if (jQuery("#checkbox").prop("checked"))
alert("first button checked");
else
alert("none checked");
}
</script>
回答by Viktor S.
This code should work:
此代码应该工作:
function testcheck()
{
if (!jQuery("#checkbox").is(":checked")) {
alert("none checked");
return false;
}
return true;
}
And here is HTML code:
这是 HTML 代码:
<input type="submit" value="Send" onclick="return testcheck()" />
return false
will stop execution of default action (form submition)
return false
将停止执行默认操作(表单提交)
回答by honyovk
FAngel is right, but I would also do this:
FAngel 是对的,但我也会这样做:
<input type="submit" value="Send" id="testcheck" />
And:
和:
$("#testcheck").on('click', function() {
if (jQuery("#checkbox").is(":checked")) {
alert("first button checked");
}
else {
alert("none checked");
}
});
回答by Salomao Davi
Dude, can be three methods using jQuery.
伙计,可以使用jQuery的三种方法。
They are: .prop(), .is() and .attr().
它们是:.prop()、.is() 和 .attr()。
As example, i will demonstrate these codes:
例如,我将演示这些代码:
function testcheck()
{
if (jQuery("#checkbox").prop("checked")){
alert("first button checked");
}
else{
alert("none checked");
}
}
function testcheck()
{
if (jQuery("#checkbox").is(":checked")){
alert("first button checked");}
else{
alert("none checked");
}
function testcheck()
{
if (jQuery("#checkbox").attr("checked")=="checked"){
alert("first button checked");}
else{
alert("none checked");}
}
Bye and Good Evening
再见,晚上好
回答by Asad Saeeduddin
This should work:
这应该有效:
function testcheck(e)
{
if (jQuery("#checkbox").prop("checked")){
alert("first button checked");
}
else{
alert("none checked");
e.preventDefault();
return false;
}
return true;
}
jQuery("#submit").click(testcheck);
I'm guessing the problem you were having was that the submit went ahead anyway.
我猜你遇到的问题是提交仍然进行。