views:

40

answers:

2

I have a page that has multiple forms. Anytime the user clicks an input or modifies text in an input I would like a function to be called. Any ideas on how to do this efficiently and in a way where it doesn't require the form IDs?

A: 
$('form input').each(function() {
     var val = this.value;
     $(this).click(function() { }
     $(this).blur(function() {
     }

});

You can also use delegate for better performance. It would help seeing your source and your exact needs.

meder
+2  A: 

JavaScript events bubble up. So how about:

$('form').change(function() {
    // do something
}).click(function() {
    // do something
});

In each case you can query for the element that triggered the event and do what you please.

AndrewDotHay
does `change` work for inputs in IE?
meder
`change` is not reliable in IE for radio buttons, checkboxes, `<select>` controls, unless you have jQuery 1.4.2, in which case a properly bubbling `change` event becomes available to IE.
Crescent Fresh
seems like that could double fire events? is there a way to make sure that doesn't happen?
AnApprentice
@nobosh: yes I'd pick one (`change` or `click`), not both. I think the example was only meant to show that you can bind to the parent `form` elements, not to each child input.
Crescent Fresh