Im having some trouble with a simple form. I can’t seem to prevent the form from submiting if the fields are empty. Is there an easy way to check if the fields are empty, and then prevent the form submitting?
Here is my html form:
<form method="post" name="simpleForm" id="simpleForm" action="handler.php">
<fieldset>
<legend>Info</legend>
<p><label for="name">Name</label><br>
<input id="name" name="name" class="text" /></p>
<p><label for="email">Email</label><br>
<input id="email" name="email" class="text" /></p>
<legend>Questions</legend>
<p><label for="qs_1">Question 1</label><br>
<input id="qs_1" name="qs_1" class="text" /></p>
<p><label for="qs_2">Question 2</label><br>
<input id="qs_2" name="qs_2" class="text" /></p>
<p><label for="qs_3">Question 3</label><br>
<input id="qs_3" name="qs_3" class="text" /></p>
</fieldset>
<p><input type="submit" name="submit" value="Send" id="sub_btn" /></p>
</form>
Here is my javascript:
$("form#simpleForm").submit(function() {
var name = $('#name').attr('value');
var email = $('#email').attr('value');
var qs_1 = $('#qs_1').attr('value');
var qs_2 = $('#qs_2').attr('value');
var qs_3 = $('#qs_3').attr('value');
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
Use
e.preventDefault()to cancel the form submission. If you want to not send an AJAX call, add a condition check. Also, use.val()instead of.attr("value").