Collins Collins - 1 year ago 90
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) {
} else {

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 Source

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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download