-1

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);
Stack Over
  • 37
  • 1
  • 6

2 Answers2

0

you don't need set interval because you are using events you will end up binding tons of event handlers which is probably causing your problem

also you should use addClass as it's more assertive

edit: remove the setInterval and call checkSignupData one time

kirinthos
  • 452
  • 2
  • 9
0
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.

wmash
  • 4,032
  • 3
  • 31
  • 69