Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 211
Jason Avatar asked Jun 24 '10 18:06

Jason


2 Answers

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
});
like image 124
Nick Craver Avatar answered Oct 03 '22 22:10

Nick Craver


Without jQuery:

function doThisOnBlur(){
// your fancy code
}

var inputs = document.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');

for (var i = 0; i < inputs.length; i++)
    inputs[i].onblur = doThisOnBlur;
for (var i = 0; i < selects.length; i++)
    selects[i].onblur = doThisOnBlur;

I made it the simplest as I could. I'd refactor that and don't assign event handlers this way, but I pointed to answer your question.

like image 22
mati Avatar answered Oct 03 '22 22:10

mati