简体   繁体   中英

jquery prevent form from submitting if fields are empty?

I am using the following code to try and change the border colour of my input boxes and prevent the form submitting if the fields are empty.

Whilst this changes the border colours, the form still submits, can someone please show me where I am going wrong here, thanks in advance

<div class="home_column">
    <div class="login_form">
        <form name="login" id="login" action="include/validate_login.php" method="post" onsubmit="return validateForm()"> 
            <h21>Username</h21><br/>
            <input type="text" class="login_form_front" id="myusername" name="myusername"><br/>

            <h21>Password</h21><br/>
            <input type="password" class="login_form_front" autocomplete="off"  id="mypassword" name="mypassword"><br/>

            <input type="submit" class="buttons_login" value="Login" id="login" name="login">
        </form> 
    </div>
</div>
function validateForm() {
    var a = document.forms["login"]["myusername"].value;
    var b = document.forms["login"]["mypassword"].value;
    if (a == null || a == "" || b == null || b == "") {
        if (a == null || a == "") { 
            document.forms["login"]["myusername"].style.borderColor = "#963634"; 
        }
        if (b == null || b == "") { 
            document.forms["login"]["mypassword"].style.borderColor = "#963634"; 
        }

        $(".form_error").show();
        $('html,body').animate({
            scrollTop: $(".form_error").offset().top - 180 
        });

        return false;
    }
}

there is an error on this line:

scrollTop: $(".form_error").offset().top - 180 

Uncaught TypeError: Cannot read property 'top' of undefined
and that's because the form_error does not exist on the html code you provided.

which make the code break and through an error before the return false line.
Everything else is ok

Pass the event object to event handler and use event.preventDefault instead of return false;

onsubmit="validateForm(event);"> 

function validateForm(event) {
  // your code
   if(conditionToStopSubmit) 
       event.preventDefault();
}

You have an odd mix of jQuery and plain JS code. Try this, attaching the event to the form submission in jQuery and using preventDefault to stop the request being made if the inputs are empty:

<form name="login" id="login" action="include/validate_login.php" method="post">
    <!-- your HTML -->
</form> 
$('#login').submit(function(e) {
    var formValid = true;
    var $username = $('#myusername');
    var $password = $('#mypassword');

    if ($username.val() == '') {
       formValid = false;
       $username.css('border-color', '#963634');
    }
    if ($password.val() == '') {
       formValid = false;
       $password.css('border-color', '#963634');
    }

    if (!formValid) {
        e.preventDefault();
        $(".form_error").show();
        $(document).animate({
            scrollTop: $(".form_error").offset().top - 180 
        });
    }
});

try add required in input text

example

<input type="text" class="login_form_front" id="myusername" name="myusername" required>

Since you're using jQuery, why not do everything in jQuery? Check out my dirty version below:

(function($) {

  $("#login").on("submit", validate);

  function validate(e) {
    var $form = $("#login"),
        $uname = $form.find("input[name='myusername']"), // or $form.find("input.login_form_front") or $form.find("#myusername")
        $pwd   = $form.find("input[name='mypassword']"),
        unameVal = $.trim($uname.val()) || "", // default ""
        pwdVal = $pwd.val() || "", // no trimming as pwd could be spaces
        isValid = true;
    if (!unameVal) {
        $uname.css({ borderColor: 'red' });
        isValid = false;
    }
    if (!pwdVal.length) {
        $pwd.css({ borderColor: 'red' });
         isValid = false;
    }
    if (!isValid) {
        e.preventDefault();
    }
  }
}(jQuery));

Live demo: Validate form submit

 <div class="home_column"> <div class="login_form"> <form name="login" id="login" action="include/validate_login.php" method="post" onsubmit="return validateForm()"> <h21>Username</h21><br/> <input type="text" class="login_form_front" id="myusername" name="myusername" required><br/> <h21>Password</h21><br/> <input type="password" class="login_form_front" autocomplete="off" id="mypassword" name="mypassword" required> <br/> <input type="submit" class="buttons_login" value="Login" id="login" name="login"> </form> </div> </div> 

try this code, And make sure that your browser is up to date.

Here I have just added a keyword "required" that is enough.

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