Reputation: 161
I want to cycle through a loop and display the status message every time the user clicks on the box, but right now it's just doing it once. I know the problem is with the next
method, how can I display the status_message until loop execution ends?
<input type='textbox' class='' name='change_box'>
<div class='alert_message'></div>
<input type='textbox' class='' name='change_box'>
<div class='alert_message'></div>
$(document).ready(function(){
$('input[name=change_box]').live({
blur: function(){
var alert_message= $(this).next('.alert_message');
for (var i=1; i<5; i++) {
if(i%2 == 0) {
alert_message.removeClass().addClass('failure').text('failed').fadeOut(500);
}
else {
alert_message.removeClass().addClass('success').text('success').fadeOut(500);
}
}
}
});
});
Upvotes: 0
Views: 62
Reputation: 55750
The problem is because of removeClass()
This removes all the classes, so you cannot select the div the next time you access it..
Try this if else loop
if (i % 2 == 0) {
alert_message.show()
.removeClass('success')
.addClass('failure').text('failed').fadeOut(500);
}
else {
alert_message.show()
.removeClass('failure')
.addClass('success').text('success').fadeOut(500);
}
Upvotes: 3
Reputation: 4190
HTML:
<input type='textbox' class='' name='change_box' id='change_box'>
<div class='alert_message'></div>
Javascript:
$(document).ready(function(){
$('#change_box').keyup(function() {
alert('Something changed.');
});
});
Upvotes: 0
Reputation: 191749
As the others have indicated, it won't trigger because of .removeClass
, but there is another problem: you hide the input and never show it again.
You should also probably be using .on
instead of .live
:
$(document).on('blur', 'input[name=change_box]', function () {
var alert_message= $(this).next('.alert_message');
...
alert_message.removeClass().addClass('failure alert_message').text('failed')
//show so it can be faded out again
.fadeOut(500, function () { $(this).show().text(''); });
});
You must make a similar change for "success"
Upvotes: 4
Reputation: 2313
When your code does removeClass()
it removes the alert_message class too, so you cannot select it on the next pass.
Your for loop should not be there either. The way it is coded right now, you run the five times every time the event is fired. Is that what you want?
Upvotes: 0