Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  186] [ 6]  / answers: 1 / hits: 20128  / 14 Years ago, thu, june 24, 2010, 12:00:00

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?


More From » jquery

 Answers
8

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

[#96415] Sunday, June 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maleahp

Total Points: 223
Total Questions: 102
Total Answers: 116

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;