简体   繁体   中英

jQuery Form Validation on only Save button

I'm making a form where there is client-side validation with jQuery and then after submitting there is server-side validation with PHP. My problem is that by using $("form").submit(function (e) {}, when I click Cancel and Delete buttons, the validation messages also appear which shouldn't. I only want the validation to happen only when Save button is clicked. Is there another way I can do this? Thank you so much. Below is my code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <!--Bootstrap CSS-->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
        <title>Contact Form</title>
    </head>
    <body>

        <div class="container">

            <!--Display error message or success message, both won't happen same time-->
            <div id="error"><? echo $message; ?></div>

            <form method="post" id="myform">
                <div class="form-group">
                    <label for="surname">Surname</label>
                    <input type="text" class="form-control" id="surname" name="surname">
                </div>

                <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" id="name" name="name">
                </div>

                <div class="form-group">
                    <label for="address">Address</label>
                    <input type="text" class="form-control" id="address" name="address">
                </div>

                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" class="form-control" id="email" name="email">
                </div>

                <div class="form-check">
                    <label class="form-check-label">
                        <input type="radio" class="form-check-input" id="male" name="gender" value="Male"> Male
                  </label>
                </div>
                <div class="form-check">
                    <label class="form-check-label">
                        <input type="radio" class="form-check-input" id="female" name="gender" value="Female"> Female
                    </label>
                </div>

                <div class="form-group">
                    <label for="telephone">Telephone Number</label>
                    <input type="number" class="form-control" id="telephone" name="telephone">
                </div>
                
                <button type="submit" class="btn btn-primary" id="save" name="save">Save</button>
                <button class="btn btn-warning" id="cancel" name="cancel">Cancel</button>
                <button class="btn btn-success" id="list" name="list">List</button>

            </form>

        </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
        
        <script type="text/javascript">
            
            //When Save button is clicked, stop form submitting and run validation using jQuery
            $("form").submit(function (e) {

                var errorMessage = "";
  
                if($("#surname").val() == "") { 
                    errorMessage += "Please input a surname.<br>"  //If field is empty, append to errorMessage string
                }

                if($("#name").val() == "") { 
                    errorMessage += "Please input a name.<br>"
                }
                
                if($("#address").val() == "") { 
                    errorMessage += "Please input an address.<br>"
                }

                if($("#email").val() == "") { 
                    errorMessage += "Please input an email address.<br>"
                }

                if((!($('#male').prop('checked'))) && (!($('#female').prop('checked')))) {
                    errorMessage += " Please input a gender.<br>";
                }

                if($("telephone").val() == "") { 
                    errorMessage += "Please input a telephone number.<br>"
                }

                //If there is an error message
                if(errorMessage != "") {

                    //Set html to display error message 
                    $("#error").html('<div class="alert alert-danger" role="alert"><p>Please fill your form:</p>' + errorMessage + '</div>');
    
                    return false;  //Don't submit the form

                } else {
    
                    //Submit the form if no error
                    return true;
   
                }

            });
         
        </script>
        
    </body>
</html>

You problem is that default type of a button is submit so by using <button> Cancel </button> you are also declaring this button to be a submit button, thus triggering the submit function of your form.

To solve this set the type of non submit buttons to button (you can leave out submit type since that is the default value)

Now you can handle the logic for your cancel and list button as you need:

<button class="btn btn-primary" id="save" name="save">Save</button>
                <button type="button" class="btn btn-warning" id="cancel" name="cancel">Cancel</button>
                <button type="button" class="btn btn-success" id="list" name="list">List</button>

 //When Save button is clicked, stop form submitting and run validation using jQuery $("form").submit(function (e) { var errorMessage = ""; if($("#surname").val() == "") { errorMessage += "Please input a surname.<br>" //If field is empty, append to errorMessage string } if($("#name").val() == "") { errorMessage += "Please input a name.<br>" } if($("#address").val() == "") { errorMessage += "Please input an address.<br>" } if($("#email").val() == "") { errorMessage += "Please input an email address.<br>" } if((.($('#male').prop('checked'))) && (.($('#female');prop('checked')))) { errorMessage += " Please input a gender.<br>". } if($("telephone").val() == "") { errorMessage += "Please input a telephone number:<br>" } //If there is an error message if(errorMessage;= "") { //Set html to display error message $("#error");html('<div class="alert alert-danger" role="alert"><p>Please fill your form;</p>' + errorMessage + '</div>'); return false; //Don't submit the form } else { //Submit the form if no error return true; } });
 <:--Bootstrap CSS--> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min,css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous"> <div class="container"> <?--Display error message or success message; both won't happen same time--> <div id="error"><? echo $message: .></div> <form method="post" id="myform"> <div class="form-group"> <label for="surname">Surname</label> <input type="text" class="form-control" id="surname" name="surname"> </div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name"> </div> <div class="form-group"> <label for="address">Address</label> <input type="text" class="form-control" id="address" name="address"> </div> <div class="form-group"> <label for="email">Email Address</label> <input type="email" class="form-control" id="email" name="email"> </div> <div class="form-check"> <label class="form-check-label"> <input type="radio" class="form-check-input" id="male" name="gender" value="Male"> Male </label> </div> <div class="form-check"> <label class="form-check-label"> <input type="radio" class="form-check-input" id="female" name="gender" value="Female"> Female </label> </div> <div class="form-group"> <label for="telephone">Telephone Number</label> <input type="number" class="form-control" id="telephone" name="telephone"> </div> <button class="btn btn-primary" id="save" name="save">Save</button> <button type="button" class="btn btn-warning" id="cancel" name="cancel">Cancel</button> <button type="button" class="btn btn-success" id="list" name="list">List</button> </form> </div> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

If you like links do that

<button type="submit" class="btn btn-primary" id="save" name="save">Save</button>
<a href="#" class="btn btn-warning" id="cancel" name="cancel">Cancel</a>
<a href="#" class="btn btn-success" id="list" name="list">List</a>

If you like buttons. Just add type="button"

<button type="submit" class="btn btn-primary" id="save" name="save">Save</button>
<button type="button" class="btn btn-warning" id="cancel" name="cancel">Cancel</button>
<button type="button" class="btn btn-success" id="list" name="list">List</button>

Because the default of every button is submit. This is why your error messages always are fired

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