简体   繁体   中英

jQuery basic form validation issue

After following an online video course, I'm having issues with a basic form validation for a simple contact form.

$("form").submit(function (e) {

    e.preventDefault();

    var error = "";

    if ($("#subject").val() == ""); {

    error += "<p>The subject area is required</p>";

    }

    $("#error").html(error);    

});

When I hit submit, the error message "The subject area is required", displays in a div with an id of "error" which is great but it happens irrespective of whether there is text in the subject box of my form or not which is where the issue lies.

I've spent a while looking but am not having much luck. I understand there is a jQuery plugin that may be better option for form validating, however, I'm still a newbie and keen to get this to work.

Any help would be greatly appreciated!

Check JQuery custom validation code

 $(function() { $("#myForm").submit(function(e) { e.preventDefault(); var fname = $('#fname').val(); if(fname.length >= 0) { $("#error").html('<font color="red">First Name is required</font>'); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <form action="" method="POST" id="myForm"> first name <input type="text" name="fname" id="fname" > <span id="error"> </span> <input type="submit" nmae="submit" value="submit"> </form> 

Try This JQuery validation code

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script> $(function() { $("#error").hide(); $("#myForm").submit(function(e) { e.preventDefault(); var fname = $('#fname').val(); if(fname.length == 0) { $("#error").show(); } else { $("#error").hide(); } }); }); </script> 
  <form action="" method="POST" id="myForm"> first name <input type="text" name="fname" id="fname" > <div id="error">First Name is required</div> <input type="submit" name="submit" value="submit"> </form> 

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