Reputation: 9647
I perform validation using the following function:
//Validation
$('.sValidate').bind('blur', function() {
if (!$(this).val()) {
$(this).removeClass('short_input');
$(this).addClass('short_input_negative');
return false;
}
});
Most of my input classes are short_input
. But some of them are also named long_input
.
How may I know what class the input
has that triggered the blur
, remove it and add long_input_negative
instead?
<input type="text" id="loginname" name="loginname" class="short_input sValidate" value="JDoe">
Upvotes: 0
Views: 143
Reputation: 87073
You can use .hasClass()
method for class detection:
$('.sValidate').bind('blur',function(){
if (!$(this).val()){
if( $(this).hasClass('long_input') ) {
$(this)
.removeClass('short_input');
.addClass('short_input_negative');
}
if( $(this).hasClass('short_input') ) {
$(this)
.removeClass('long_input');
.addClass('long_input_negative');
}
}
});
From jQuery doc about .hasClass()
Determine whether any of the matched elements are assigned the given class.
Another way is using .is()
$('.sValidate').bind('blur',function(){
if (!$(this).val()){
if( $(this).is('.long_input') ) {
// do something of long_input
}
if( $(this).is('.short_input') ) {
// do something of short_input
}
}
});
From jQuery doc about .is()
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
Upvotes: 6
Reputation: 18064
Here this line !$(this).val()
returns false
, if there is some value. So condition never executes.
Do this way:-
$('.sValidate').bind('blur',function(){
if ($(this).val().length > 0){
if ($(this).hasClass('short_input')) {
$(this).removeClass('short_input');
$(this).addClass('short_input_negative');
}
if ($(this).hasClass('long_input')) {
$(this).removeClass('long_input');
$(this).addClass('long_input_negative');
}
}
});
Refer to LIVE DEMO
Upvotes: 0
Reputation: 13557
While @thecodeparadox has answered your original question, I'd like to point out that »you're doing it wrong«™ - without knowing what your classes actually do. I'm guessing the foo_negative
class is supposed to switch the color to red or something similarly mundane.
.short_input {
width: 50px;
}
.long_input {
width: 100px;
}
.negative {
color: red;
}
now that allows you to keep the short_input
and long_input
classes and simply add/remove the negative
class to alter your styling. If you didn't know this, have a look at MDN CSS.
Upvotes: 0