简体   繁体   中英

jQuery basic form validation if or

this is not working and i cant really see anything wrong with it, looks straightforward enough:

            $("#formLogin").submit(function(){
                var username = $("#username").val();
                var password = $("#password").val();
                if (username == ' ' || password == ' '){
                    return false;
                }
                else return true;
            });

EDIT:

Its still submitting the form even if the fields are empty

Are you trying to detect blank usernames and passwords?

  $("#formLogin").submit(function(){
            var username = $("#username").val();
            var password = $("#password").val();
            if (jquery.trim(username) == '' || jquery.trim(password) == ''){
                return false;
            }
            else return true;
        });

jquery.trim() removes leading and trailing spaces, so just in case the user types a number of space characters it will be detected.

In the html add this <input type="submit" value="SomeButton" onclick="return submitClicked();" /> <input type="submit" value="SomeButton" onclick="return submitClicked();" />

in the js do this

function submitClicked() {
    if ($("#passwordInput").val() == '')
    {
        alert('missing password field');
        return false;
    }

Instead of doing this, why not simply use the jQuery Validation Plugin - http://docs.jquery.com/Plugins/validation

VALIDATE FORMS LIKE YOU'VE NEVER BEEN VALIDATING BEFORE! (According to the site)

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