简体   繁体   中英

check multiple input values with javascript and marking multiple input boxes on 1 check

I expected the following function to apply a red border to BOTH the input field with id 'name', AS the input field with the id 'email'. (when the user leaves all input-fields empty)

However, the script only applies the red border to the input-field with id 'name', and leaves the field with id 'email' untouched.

            function checkform() {
                if ( name() && mail() ) {
                    return true;
                } else {
                    return false;
                }
            }

            function name() {
                if (document.getElementById("name").value == "") {
                    $("#name").css("border", "1px solid red");
                    return false;
                } else { 
                    return true; 
                }
            }

            function mail() {
                if (document.getElementById("email").value == "") {
                    $("#email").css("border", "1px solid red");
                    return false;
                } else { 
                    return true; 
                }
           }

It seems like the return false in the sub-function 'name()' somehow 'kills' the entire code, and stops 'mail()' from every being run.

Update : If I switch the function-names in the 2nd line only the input-field with id 'email' gets a red border (if user leaves all input-fields empty). Then the field with id 'name' remains untouched.

(Sorry for using javascript and jquery at the same time)

The return false statement in the name function is short-circuiting the statement inside the if condition. While evaluating if( name() && mail() ), name() returns false and since AND with false always gives false, the statement is short-circuited and the mail() function is never called.

If statement runs the conditions one by one until it is sure that they don't fulfill the condition. In your case if name() is false it will never run the conditions after it. In your case you can try using something like:

function checkform() {
   var isValid = name();
   isValid = mail() && isValid;
   return isValid;
}

However I recommend you to write a generic function that will check if some input given as parameter is empty.

Also there is quite nice jQuery plugin that might help you with your task: http://jqueryvalidation.org/

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