Stack Over Stack Over - 5 months ago 11
jQuery Question

Didn't updating class for element - jQuery

After blur, if input is empty, i want to add class .hass-error, after that i write some text into input, on idea class .hass-error must removed and added class has-success. .has-error is removing but new clas

function checkSignupData() {
var username = $('.signup-panel input[name="username"]');

username.on({
'focusin': function(){},
'focusout': function(){
if(!this.value.length) {
$(this).closest('.form-group').removeClass('has-success').toggleClass('has-error');
}
else if(this.value.length > 3 && this.value.length < 32) {
$(this).closest('.form-group').removeClass('has-error').toggleClass('has-success');
}
}
});
}
setInterval(checkSignupData(), 100);

Answer
function checkSignupData() {
   var username = $('.signup-panel input[name="username"]');

   if (username.text().length > 0) {  
       username.closest('.form-group').removeClass().addClass('has-success');
   } else {
       username.closest('.form-group').removeClass().addClass('has-error');
   }
}

window.setInterval(function(){
    checkSignupData();
}, 5000);

This is not an ideal solution using setInterval as the DOM will become messy and slow your application. For example, if this username is within a form, then you can call the check when the form is submitted. Like I said, not the most ideal solution but the one I think you are trying to achieve.

checkSignupData() will be called every 5 seconds.

Another solution I have just thought of which may work:

username.on('keyup', function() {
    // call function
});

I originally thought this may not work as it would not fire if nothing was in the input. However, pressing a backspace to remove text will trigger the event as well. The only think is that on start up, you will have to initialise the element to have has-error class as there will be initially nothing in it.