Reputation: 9855
i have a form that when submitted, if any field is empty id like to prevent the submission and add a class to the field.
For some reason I cant seem to get it too work, Ive added a fiddle, can anybody point out where im goign wrong?
Upvotes: 0
Views: 88
Reputation: 7246
Rather than preventDefault(), returning false in the function that calls the form when submitted also prevents submitting. In the previous answer, let's think that there are more than one empty fields, preventDefault() will be unnecessarily fired more than once.
I would use something like this as a cleaner solution:
$(document).ready(function(){
$("#form").submit(function(e) {
var submit=true; //A flag that we'll return
$('input').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
submit=false //Setting the flag to false will prevent form to be submitted
}
});
return submit;
});
});
Upvotes: 0
Reputation: 87073
$(document).ready(function() {
$("#form").submit(function(e, a) {
$('input, textarea', this).each(function() {
if (!$(this).val()) {
$(this).addClass('highlight');
e.preventDefault();
} else($(this).hasClass('highlight')) ? $(this).removeClass('highlight') : false; // remove class on valid
});
});
});
Upvotes: 0
Reputation: 20591
Apart from not calling preventDefault
, you are using $this
instead of this
in one place and the brackets don't match. Working version:
Upvotes: 0
Reputation: 165971
There are a couple of problems with your fiddle. Firstly, you haven't closed the ready
event handler. Secondly, are passing $this
into jQuery which is undefined
. You need to pass this
instead.
Finally, the form is always going to be submitted because you have to actually stop the submission. You can call the preventDefault
method of the event object to do so. Here's a new version of your code:
$(document).ready(function(){
$("#form").submit(function(e) {
$('input').each(function() {
if ($(this).val() == '') { //Pass this into jQuery, not $this
$(this).addClass('highlight');
e.preventDefault(); //Stop the form from submitting
}
});
});
});
Also note that it's unnecessary to use $(this).val()
inside the each
loop. this
will be a reference to a DOM element, and that element will have a value
property, so it's more efficient to simply use this.value
.
Upvotes: 4
Reputation: 34837
You're not stopping the form from actually being submitted and thus it still gets posted (and thus immediately dropping your highlights). Try adding the preventDefault method to your form and manually submit after checking for errors.
Upvotes: 1