views:

34

answers:

2

I have a long a web form. I'm wondering if I should bind() to each element separately (what I really want) or should I only define one bind() all of the input elements then do an if-then inside the handler to handle the specific element?

+3  A: 

jQuery's event handlers are implemented in JavaScript (they have to be).

In general, it's best to use a single handler for the entire form, rather than a large number of individual elements. But jQuery's live feature can help quite a lot, it does a lot of the plumbing for event delegation for you. For example:

$("#formid input").live('focus', function(event) {
    var field = $(this);
    // `field` now references the field that was focussed
});

...watches all fields in your formid form for focus events. If you're using jQuery 1.4, that works even with the focus event in that example (even though focus doesn't bubble, and so is usually tricky to use with event delegation). Prior to 1.4 that won't work, but bubbling events like click and such do.

T.J. Crowder
Thanks! ".live" is really great. I used it and luv it.
Pete Alvin
A: 

I would bind to all the inputs, but you can use classes to narrow it down to just the inputs you want.

Instead of

$("#formid input").click(function() { 
  if($(this).attr('something') == 'special_field') {
    //do A
  }
});

add a class to the elements you are interested in <input class='special_field' ... >, and change your selector:

$("#formid input.special_field").click(function() { 
    //do A
});

That will limit the handler to only the desired elements without any if statement checks.

You can repeat this for anything that needs special handling.

Final note on the .live() method. It can be really handy for a couple reasons:

  1. It doesn't actually create a binding for every matching element, it creates a listener on the body element by default(you can choose another element as the listener) and waits for an even to bubble up to it. When it bubbles, it checks the triggered element against the selector, and if its a match fires the event.
  2. Because the selector is applied when the event fires, it means that new elements added via Javascript or AJAX will fire the code without needing to bind or rebind them.
  3. There is one listener for many elements, meaning for large sets it can be much quicker.
Tilendor