确保至少选中一个复选框

编程入门 行业动态 更新时间:2024-10-23 19:32:11
本文介绍了确保至少选中一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有多个复选框的表单,我想使用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.

更多推荐

确保至少选中一个复选框

本文发布于:2023-11-04 00:57:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复选框

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!