简体   繁体   中英

How to validate specific aspects of a web form?

Being fairly new to JavaScript, I am struggling with how to target and validate specific areas of a form.

I have created a simple web form, which consists of two text input fields for first name and last name. A checkbox with four options, and a submit button. With the form created, I wish to ensure the user:

  1. Supplies their first and last names.
  2. Exactly one checkbox is selected.
  3. If either of the two above fail, an error message should be displayed with all the errors specifying the problem exactly, ie if too many checkboxes have been selected, or none at all.

I have attempted number 2 and have so far got the following:

function checkBox (){
var cbx = document.getElementById("myForm").cbx;
var chbx = false;
for (i=0; <cbx.length; i++) { 
    if(cbx[i].checked){
chbx = true; 
// if not produce an alert
if (!chbx) {
    alert("No checkboxes selected"); 
}

If the above is functionally correct, it only works when no checkboxes are selected, what if too many are selected? How do i go about these three problems?

First things first, you have some syntax errors. Please try the following code and see if it's working any better.

function checkBox (){
    var cbx = document.getElementById("myForm").cbx;
    var chbx = false;
    for (i=0; <cbx.length; i++) { 
        if(cbx[i].checked){
            chbx = true; 
            // if not produce an alert
            }
        if (!chbx) {
            alert("No checkboxes selected"); 
        }
    }
}

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