I am doing a form validation, and I wish that all inputs that were empty adds the class "error", now I got only one at a time.
jQuery
$(".text-input").blur(function () {
if ($(this).val() == '') {
$(this).addClass('error');
}
});
I am doing a form validation, and I wish that all inputs that were empty adds the class "error", now I got only one at a time.
jQuery
$(".text-input").blur(function () {
if ($(this).val() == '') {
$(this).addClass('error');
}
});
You might also want to restore the nonerror and check for whitespaces: demo
var inp = $('.text-input'); // Cache your selectors
inp.blur(function () { // On blur...
inp.removeClass('error').filter(function(){ // Remove error classes. Filter
return !$.trim(this.value); // to return el. without value
}).addClass('error'); // and assign error class.
});
Another way to do it: demo
var inp = $('.text-input');
function err(){
$.each(inp, function(){
$(this).toggleClass('error', !$.trim(this.value));
});
}
inp.blur(err);
Using the classic if demo
var inp = $('.text-input');
function err(){
$.each(inp, function(){
if(!$.trim(this.value)){
$(this).addClass('error');
// more stuff
}else{
$(this).removeClass('error');
// more stuff
}
});
}
inp.blur(err);
The decision of adding the error class should also happen at the start; to do this, you can write a small function that will be run either at the start or whenever the blur event occurs.
Also, you can simplify the logic of adding or removing the error class by using .toggleClass().
function updateInputClass()
{
$(this).toggleClass('error', $.trim(this.value) == '');
}
$(".text-input")
.blur(updateInputClass)
.each(updateInputClass)
_°g°_ <- teddy is watching you ;)