Reputation: 413
I have an easy keyup function for class "keyup-an" for keyup validation on a form. There are about 10 fields with this class. However after post, I add fields to the form. But the background of green and red goes away because its not keyup. How do i do something like this each that will color the backgrounds based on this result on page load
jQuery(document).ready(function() {
$('.keyup-an').each(function(index) {
var inputVal = $(this).val();
var numericReg = /^[a-zA-Z0-9_ ]{2,30}$/;
if(!numericReg.test(inputVal)) {
$(this).css('background', '#FAC3C3');
$(this).after('<span class="error error-keyup-1">Please use letters or numbers only</span>');
}
else {
$(this).css('background', 'lightgreen');
}
});
$('.keyup-an').keyup(function() {
$('span.error-keyup-1').hide();
var inputVal = $(this).val();
var numericReg = /^[a-zA-Z0-9_ ]{2,30}$/;
if(!numericReg.test(inputVal)) {
$(this).css('background', '#FAC3C3');
$(this).after('<span class="error error-keyup-1">Please use letters or numbers only</span>');
}
else {
$(this).css('background', 'lightgreen');
}
});
Upvotes: 2
Views: 3005
Reputation: 7335
I guess this is what you wanted..
$(document).ready(function() {
// Each
$('.keyup-an').each(function() {
// Validate
validate(this);
// Key up
$(this).keyup(function(){
// Validate
validate(this);
});
});
});
// Validate Function
function validate(element) {
var obj = $(element);
if(!/^[a-zA-Z0-9_ ]{2,30}$/.test(obj.val())) {
// Invalid
obj.css('background', '#FAC3C3');
if(!obj.next().hasClass('error'))
{ obj.after('<span class="error error-keyup-1">Please use letters or numbers only</span>'); }
} else {
// Valid
obj.css('background', 'lightgreen');
if(obj.next().hasClass('error'))
{ obj.next().remove(); }
}
}
Demo: http://jsfiddle.net/BerkerYuceer/q2ajM/
Upvotes: 2
Reputation: 14025
You should define your keyup events like this. By the way, if your elements form are created dinamically, you must bind events with .on()
jQuery(document).ready(function() {
$('.keyup-an').each(function(index) {
$(this).keyup(function() {
var inputVal = $(this).val();
var numericReg = /^[a-zA-Z0-9_ ]{2,30}$/;
if(!numericReg.test(inputVal)) {
$(this).css('background', '#FAC3C3');
$(this).after('<span class="error error-keyup-1">Please use letters or numbers only</span>');
}
else {
$(this).css('background', 'lightgreen');
}
});
});
}
Upvotes: 0
Reputation: 413
$('.keyup-an').each(function(index) {
var inputVal = $(this).val();
var numericReg = /^[a-zA-Z0-9_ ]{2,30}$/;
if(!numericReg.test(inputVal)) {
$(this).css('background', '#FAC3C3');
$(this).after('<span class="error error-keyup-1">Please use letters or numbers only</span>');
}
else {
$(this).css('background', 'lightgreen');
}
});
Upvotes: 1