确保至少选中一个复选框 [英] Making sure at least one checkbox is checked

查看:501
本文介绍了确保至少选中一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个复选框的表单,我想使用javascript来确保至少有一个被选中。这是我现在的情况,但不管选择什么,警报弹出。

I have a form with multiple check boxes and I want to use javascript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.

<html>
<head>
<script language="javascript">
<!---

function valthis()
{


if (document.FC.c1.checked)
{
alert ("thank you for checking a checkbox")
}
else
{
alert ("please check a checkbox")
}


}

-->
</script>
</head>
<body>

Please select at least one Checkbox
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"> C1 <br>
<input type = "checkbox" name = "c1" value = "c2"> C2 <br>
<input type = "checkbox" name = "c1" value = "c3"> C3 <br>
<input type = "checkbox" name = "c1" value = "c4"> C4 <br>
</form>
<br>
<br>

<input type = "button" value = "Edit and Report" onClick = "valthisform();">
</body>
</html>

我最后做的是这

function valthisform()
{
var chkd = document.FC.c1.checked || document.FC.c2.checked|| document.FC.c3.checked|| document.FC.c4.checked

if (chkd == true)
{
}
else
{
alert ("please check a checkbox")
}

}

删除谢谢部分适合其余的作业。非常感谢你,每个人的建议真的帮助了。

I decided to drop the Thank you part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.

推荐答案

如果计划引用文档,则应避免使用两个具有相同名称的复选框。 FC.c1 。如果您有多个名为 c1 的复选框,浏览器将如何知道您要引用哪个?

You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?

jQuery解决方案来检查是否选中页面上的任何复选框。

Here's a non-jQuery solution to check if any checkboxes on the page are checked.

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);

您需要 Array.prototype.slice.call part将 document.querySelectorAll 返回的 NodeList 转换为可以调用一些

You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.

这篇关于确保至少选中一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆