Reputation: 1825
I'm showing errors in the above fields, but I want to add styling near it, e.g., add some image as background into the containing div.
I'm adding it like this:
$('input').change(function() {
if ($(this).hasClass('valid')) {
$(".field2").has(this).removeClass('bg2').addClass('bg1');
}
if ($(this).hasClass('error')) {
$(".field2").has(this).removeClass('bg1').addClass('bg2');
}
})
and css:
.bg1
{
background-image: url('valid.png');
background-repeat: no-repeat;
background-position:320px 25px;
}
.bg2
{
background-image: url('not_valid.png');
background-repeat: no-repeat;
background-position:320px 25px;
}
But now it working like this:
I want to make background appears together with fields.
Can do it using simple jQuery events? OR
Should I add error labels for this? If so - please, supply an example of validation with form and labels WITHOUT error text if it is possible.
Upvotes: 0
Views: 181
Reputation: 7090
As Saeed Py said, you should use keyup/keydown event instead of change. The problem with chance event is that it is triggered only when the input element loose the focus.
You could change it for either keydown/keyup/keypress to validate input on every key press. You could also add click event, in the case of a user pasting data with the mouse only.
I have made a quite simple jsfiddle demoing the difference between those 3 events. (It's kinda incomplete as I didn't use any field validation...).
As for your javascript, it should probably be more like this :
if ($(this).hasClass('valid')) {
$(".field2").has(this).removeClass('bg2').addClass('bg1');
}
Should probably be written as
if ($(this).hasClass('valid')) {
$(".field2").has($(this)).removeClass('bg2').addClass('bg1');
}
this -> $(this)
Of course, this depends on more markup then what you showed us. I'm assuming a div with a common class surrounding each input, as displayed in my jsfiddle.
Upvotes: 1