I was wondering what I was doing wrong here. The first function runs just fine when the reset button is called, but for some reason the second function isn't doing anything. The form does get reset but the second alert never pops up and the warn class is never removed. Thanks for your help!
$('#registration :reset').click(function() {
alert("reset was clicked");
$('#registration :text').each(function() {
if ($(this).hasclass('warn')) {
$(this).removeClass('warn');
}
if (!$(this).hasclass('texta')) {
开发者_开发问答 $(this).addClass('texta');
}
alert("value");
});
});
The Javascript language is case-sensitive. The hasclass()
method does not exist, but hasClass() does. You should write:
$('#registration :text').each(function() {
if ($(this).hasClass('warn')) {
$(this).removeClass('warn');
}
if (!$(this).hasClass('texta')) {
$(this).addClass('texta');
}
alert("value");
});
That said, you usually don't need to call hasClass()
before addClass() or removeClass(), because addClass()
won't add a duplicate if the element already has the class you specify, and removeClass()
won't remove a class the element doesn't have. So you can simply write:
$('#registration :text').each(function() {
$(this).removeClass('warn');
$(this).addClass('texta');
alert("value");
});
Or, using method chaining like @deceze does:
$('#registration :text').each(function() {
$(this).removeClass('warn').addClass('texta');
alert("value");
});
Try this instead:
$('#registration :text').removeClass('warn').addClass('texta');
Behold ze Magik of jQuery!
Pretty much every jQuery method works on every element returned by the $
function. So there's no need to loop through all results, removeClass
and addClass
will be applied to all elements found by the #registration :text
selector. Furthermore, there's no need to do any checking before removing or adding classes. If you're adding the class and the element already has the class, nothing happens. Vice versa for removing a class.
Try reading a tutorial, this is what makes jQuery so powerful!
Try to use live , as they are getting added and removed ,
i think when you remove they are getting un binded..
$('#registration :reset').live('click', function() {
alert("reset was clicked");
$('#registration :text').each(function() {
if ($(this).hasClass('warn')) {
$(this).removeClass('warn');
}
if (!$(this).hasClass('texta')) {
$(this).addClass('texta');
}
alert("value");
});
});
精彩评论