I would like to check if a text field in the post form is empty before posting using jquery. If any, I would like to display an error message right next to the text area. I click the button to submit the information with empty fields but there are no messages displayed. I need this check function before the posting is perform. Here is what I have done.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.7.1.min.js"></script>
<script>
function ValidateForm()
{
$(document).ready(function(
{
$("#personID").each(function()
{
if(this.val()=="")
{
$("#error_msg").html("Field needs filling");
}
}
}
));
}
</script>
</head>
<body>
<form action="action.php" method="post" id="personID">
First Name: <input type="text" name="first"><span id="error_msg"></span></br>
Last Name: <input type="text" name="last"><span id="error_msg"></span></br>
Phone: <input type="text" name="phone"><span id="error_msg"></span></br>
Mobile: <input type="text" name="mobile"></br>
Position: <input type="text" name "pos"><span id="error_msg"></span></br>
<input type="button" value="Insert" onclick="ValidateForm">
</form>
</body>
</html>
The function should be
and your form should be
You didn’t added any span next to your phone textbox and if it remains empty the form won’t be submitted and it won’t display error message as well, so be sure about it. If you want to leave it optional then add a class to it
(class='optional')and change the functionif($(this).val()=="")toif($(this).val()=="" && !$(this).hasClass('optional')). that’s it.