Collins Collins - 3 months ago 8
jQuery Question

jQuery blur not working on page load

I have this bit of jQuery...

$('.group-guest-list input.form-text').blur(function() {
if(!$.trim(this.value).length) {
$(this).closest('div').addClass('disabled');
} else {
$(this).closest('div').removeClass('disabled');
}
});


It checks to see if a text input is empty, and adds a "disabled" class if it is.

This only works if you click inside the field, and then click out again. On the first page load, the class isnt there. I need it to react on blur so that when the field is emptied it is disabled.

Can someone help to make this run on page load, as well as on focus? Thanks.

Answer

You can use bind multiple events using .on() and use .trigger() to execute the event handler on page load.

$('.group-guest-list input.form-text').on('blur focus', function() {
  $(this).closest('div').toggleClass('disabled', !$.trim(this.value).length);
}).trigger('blur');

Additionally, You can use .toggleClass( className, state )