Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if input field is empty on fields with jQuery

I have a form with 5 fields all with the class 'required'

Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.

$('.submit').click(function(){

if($('.required').val() == "") {
        $('.required').addClass('error');
        return false;
    } else {
        return true;
    };
});
like image 413
Liam Avatar asked Mar 22 '13 16:03

Liam


2 Answers

Try:

$('.submit').click(function(e){
 if(!$('.required').val()) {
    $('.required').addClass('error');
    e.preventDefault();
  } else {
    return true;
  };
});
like image 179
Anujith Avatar answered Oct 03 '22 11:10

Anujith


Try this:

$('.submit').click(function() {
    $('.required').removeClass('error').filter(function() {
        return !$.trim(this.value).length;
    }).addClass('error');
});

Class error is added to empty fields only and is removed otherwise.

http://jsfiddle.net/dfsq/2HxaF/

Another variation which can be useful for your task: additional validation on fields blur:

$('.submit').click(validate);
$(document).on('blur', '.required', function() {
    validate($(this));
});

function validate($field) {
    ($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
        return !$.trim(this.value).length;
    }).addClass('error');
}

http://jsfiddle.net/dfsq/2HxaF/1/

like image 31
dfsq Avatar answered Oct 03 '22 10:10

dfsq