Mohammad Istanboli Mohammad Istanboli - 6 months ago 7
HTML Question

how to stop a form from submitting without disable the button with JQuery?

hello I have a simple form to validate I want to do a client side validation lets say that my form has only one field for name I want to check if the name length is between 5 and 20 chars if yes then no problem and the data will be sent to the server and then apply a server side validation ;however, if it's not then an error message will be displayed in a span beside the input field says that it must be 5 to 20 chars.The problem is when I hit the submit button it shows the result for less than a second then it goes cause the submit button reload the page which also means if I have included my server side validation it will also be processed since the input data already sent so how can I stop the submit button from sending data to the server and reloading the page without disabling the button.

here is my example code

<!doctype html>
<html>
<head>
<title>form validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<script>
$( document ).ready(function() {
$("#submit").click(function(){
myfunction();
});

function myfunction()
{
name = $("#user").val();
nameError = $(".error").first();
myError = "";
if(name.length < 5 || name.length > 20)
myError += "length should be between 5 and 20 ";
else
myError += "ok"

nameError.html(myError);

}
});
</script>

<style>
.error
{
color : red;
text-transform: capitalize;
margin-left: 20px;
}
</style>
</head>
<body>

<form method="post" action="">
NAME : <input type="text" name="user" id="user"><span class="error"></span><br />
<input type="submit" value="Submit" id="submit">
</form>

</body>
</html>

Answer

The problem is you're not canceling form submission on finding a problem.

To do this you'll need to listen for a submission event on the form, not a click event on the button.

Try:

       $("form").on('submit', myfunction); //<-- listen for form submit, not button click

        function myfunction(evt) { //<-- the event object is automatically passed along;
                                   //    this is key for suppressing submission
            name = $("#user").val();
            nameError = $(".error").first();
            myError = "";
            if(name.length < 5 || name.length > 20)
                myError += "length should be between 5 and 20 ";
            else
                myError += "ok"

            if (myError) {
                evt.preventDefault(); //<-- suppress submission if error found
                nameError.html(myError);
            }

        }

You could alternatively use HTML5 validation and make your life a little easier.

Comments