Jason Jason - 1 month ago 12
Javascript Question

Add an onBlur to all form elements

So on a specific page I have some number of form elements, anywhere between 3 and 8, depending upon the user and their action on the page.

How can I add a specific onblur event to all of the form elements dynamically on the page?

If I have:

function doThisOnBlur() { stuff }


How can I add that same function to all of these once the page loads. No elements are created after the page loads but different elements may appear for different users.

<input type="text" id="x">
<input type="text" id="y">
<select id="z">...</select>


Is that possible?

Answer

Edit: For updated question
Use .blur() and an anonymous function for this (doesn't matter how many elements there are):

$(":input").blur(function() {
  //do stuff
});

If you need to bind certain functions to certain fields, use classes or an attribute selector on name, anything to distinguish them...if the selector doesn't find an element it simply won't bind an event handler to anything. That way, the same overall code works for all users, even if they only see some of the form elements available.


For original question: if elements were dynamically added after page-load.
I think .live() to capture the blur event is what you're after here, using :input as the selector:

$(":input").live('blur', function() {
  //do stuff
});