views:

127

answers:

1

I'm trying to determine when any of a set of named input/select/radio/checked/hidden fields in a form change.

In particular, I'd like to capture when any changes are made to fields matching jQuery's selector $("form :input"), and where that input is has a name attribute. However, the form isn't static i.e. some of the fields are dynamically added later.

My initial thought is to keep track of when new named elements matching :input are added, and then add an event handler, like this:

function on_change() {
   alert("The form element with name " + $(this).attr("name") + " has changed");
}

function reg_new_e_handler(input_element) {
    input_element.change(on_change);
}

However, I'm quite hopeful I can avoid this with some jQuery magic. In particular, is there a way to register an event handler in jQuery that would handle input elements that match the following:

$("form :input").filter( function () { $(this).attr("name") } ).change(on_change);

However, have this event set update whenever new input elements are added.

I've thought that it may be possible to capture keyup event on the form node with $("form").keyup(on_change), but I'm not so sure how one could capture change events.

I'd also like this to capture keyup events.

Thank you for reading.

Brian

+3  A: 

You're looking for live events.
For example:

$(':input[name="something"]'.live('change', function(e) {
    //Do things
});

Adding an event handler using .live will handle the event for all elements that match the selector, no matter when they were added.

SLaks
You could just do :input[name] to get all named elements.
Paolo Bergantino
Yes, `$(':input[name]').live('change onkeyup', foo);` works as expected. That's wickedly cool!
Brian M. Hunt