views:

236

answers:

5

Basically I'd like to bind function A to all inputs. Something like this:

$('input').bind('change', function() { bla bla bla });

And then later I would like to bind something different in addition like this:

$('#inputName').bind('change', function() { do additional processing..});

Is that possible? Does it work? Am I missing the syntax? Is that fine actually fine (meaning I have a bug elsewhere that's causing one of these not to bind)?

A: 

In your code, one is input, and the other inputName, is that a typo?

Searched, there is a similar question here.

$(document).ready(function() {
  $("input").change(function() {
    console.log("function1");
  });

  $("input").change(function() {
    console.log("function2");
  });
});
J.W.
Not a typo, just the simplest way to show the differentiation
Jared
A: 

assuming the above is resolved (i.e. you're trying to bind a function to the same object), yes, you can bind multiple event handlers to the same one.

to make your life easier, look into namespaces for this as well (so you can group event handlers for the same event).

Oren Mazor
+2  A: 

The short answer to your question is YES.

If you wish to bind additional functionality to the change event of #inputName, your code sample should work.

If you wish to alter the function that handles the event you can unbind all handlers of the change event before you rebind any new event handlers like so...

$('#inputName').unbind('change');

but be careful... w/o trying this out I am unsure of any of the side affects.

Jon Erickson
A: 

Why don't you create a function that call them both, and then bind this new function to the event?

Samuel Carrijo
A: 

It works fine to bind both. Where it gets slightly interesting is when you're trying to prevent default behavior by returning false. The bound functions cannot prevent each other from running that way, but they can prevent parent elements' event handlers from running.

chaos