简体   繁体   English

表单验证-多个复选框

[英]Form Validation - Multiple checkboxes

I need to ensure that if at least one checkbox (of many) is not ticked, the form wont submit, this is what I have at the moment, I thought it should work: 我需要确保如果没有选中(多个)至少一个复选框,则表单不会提交,这是我目前所拥有的,我认为它应该可以工作:

<script type="text/javascript">
function valthis() {
 var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
 var isChecked = false;
 for (var i = 0; i < checkBoxes.length; i++) {
    if ( checkBoxes[i].checked ) {
        isChecked = true;
    };
    };
    if ( !isChecked ) {

    alert( 'Please, check at least one checkbox!' );
    return false;
    }   
   }

</script>  

I would appreciate any help I can get!!! 我将不胜感激,我可以获得!

regards, Mason. 问候,梅森。

This looks good but you to call valthis() before submitting the form, which you would do "manually" in your code after validating that everything is OK. 这看起来不错,但是您可以在提交表单之前调用valthis() ,在确认一切正常之后,可以在代码中“手动”执行此操作。

Basically, this means that you have a basic button (not a "submit" one) that actually calls valthis : 基本上,这意味着您有一个实际调用valthis的基本按钮(而不是“提交”按钮):

<input type="button" onClick="valthis()" ></input>

Then at the end of valthis() : 然后在valthis()结尾:

document.getElementById("myForm").submit();

You have not provided much detail about your actual problem so it's impossible to say exactly what is going wrong. 您没有提供有关实际问题的详细信息,因此无法确切地说出问题所在。

This is what you should have, whether it's what you actually have is moot. 这就是您应该拥有的,无论您实际拥有的是什么。 There should be a submit listener on the form: 表单上应该有一个提交侦听器:

<form onsubmit="return valthis(this)" ... >

There should be a submit button in the form: 表单中应该有一个提交按钮:

<input type="submit">

or 要么

<button>Submit</button>

The submit listener should return false to cancel submission, or any other value to not cancel. 提交侦听器应返回false以取消提交,或者返回任何其他值以不取消。 The function should have a more meaningful name, say "checkCheckboxes", and the loop can return as soon as a checked checkbox is found: 该函数应具有更有意义的名称,例如“ checkCheckboxes”,并且一旦找到选中的复选框,循环就可以返回:

function valthis() {

  var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
  var isChecked = false;

  // Break from loop if isChecked is true
  for (var i = 0; i < checkBoxes.length && !isChecked; i++) {
    isChecked = checkBoxes[i].checked;
  }

  return isChecked;
}

There is no need for a semicolon after a block, it will represent an empty statement (nothing harmful, just redundant). 块后不需要分号,它将表示一个空语句(无害,只是多余的)。

If you could guarantee support for modern APIs, then: 如果可以保证对现代API的支持,则:

<form onsubmit="return this.querySelectorAll('input[type=checkbox]:checked').length > 0;" ...>

would do. 会做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM