tags:

views:

89

answers:

4

Is there a better way to do this jQuery selection:

$("p.DynFieldWrapper :input:not(:text):not(textarea)").focus(HideDynamicFormError).click(HideDynamicFormError);
$("p.DynFieldWrapper :text,p.DynFieldWrapper textarea").blur(HideDynamicFormError);

I am binding my function, HideDynamicFormError, to the blur event for textboxes and textareas and to the focus and click events of other form input elements.

This is working but I am still getting the hang of things in jQuery, and was wondering if there was a better way of doing this?

+1  A: 

The first one can be a little simpler:

$("p.DynFieldWrapper :input:not(:text,textarea)")

Other than that, you're doing fine.

chaos
+1  A: 

I'd be tempted to do this:

$("p.DynFieldWrapper :input").each(function() {
  if ($(this).is(":text") || $(this).is("textarea")) {
    $(this).blur(HideDynamicFormError);
  } else {
    $(this).focus(HideDynamicFormError).click(HideDynamicFormError);
  }
});

I don't know if (performance-wise) how this compares with what you're doing. It might be better. It might be worse. It's worth testing though.

There is nothing wrong with what you're doing. I'm just not sure how fast all the p finds plus all the subtree traversals looking for form elements will be. It may well depend on the size of your document and the relevant subtrees.

cletus
A: 

You can use bind() to bind an event handler to multiple events too. Using p.DynFieldWrapper as a context may be faster too, you'll need to performance test this though.

$("input:not(:text,:textarea)", "p.DynFieldWrapper")
    .bind("focus click", HideDynamicFormError);
Russ Cam
I think you need to replace the comma with a space between focus and click
Ronnie Overby
Right you are, thanks :)
Russ Cam
A: 

Merging all the above answers + throwing in my idea of using find, how about this?

$('p.DynFieldWrapper :input')
    .find(':not(:text, textarea)')
       .bind('focus click', HideDynamicFormError)
    .end()
    .find(':text, textarea')
       .blur(HideDynamicFormError);

EDIT:

Another idea, just for fun! (though I don't like it myself)

$('p.DynFieldWrapper :input')
    .bind('focus click blur',
        function(ev)
        {
            if($(this).is(':text, textarea'))
            {
                if(ev.type == 'blur')
                    HideDynamicFormError(ev);
            }
            else
            {
                if(ev.type != 'blur')
                    HideDynamicFormError(ev);
            }

        }
    );
SolutionYogi