简体   繁体   中英

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.

Basically, this means that you have a basic button (not a "submit" one) that actually calls valthis :

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

Then at the end of 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. The function should have a more meaningful name, say "checkCheckboxes", and the loop can return as soon as a checked checkbox is found:

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:

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

would do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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