I’m using jQuery 1.7 and need to bind the same function to 2 different live events on 2 different selectors, like:
function do_something(_this){
// do something with _this
alert("test");
}
$("input").live("keyup", function({
do_something($(this));
});
$("select").live("change", function({
do_something($(this));
});
This works, but I would really like if I could somehow pull all this into one statement, like:
// pseudo code
( $("input").live("keyup") || $("select").live("change") ).bind(function(){
// do something with $(this)
alert("test");
});
Is that possible?
You can put the
do_something()function into the.live()function directly and avoid the anonymous function. That saves a few characters.To convert to the jQuery 1.7 syntax, you need to use a delegate (which
.live()did for you). You can use the<form>where your input and select elements are or thedocument.And if you really want to put both events and selectors in one call, you can. Since you’re going to the same function anyway, and since you’re using a delegate there are only two events total. If you really think you need it, you can check the event in the callback to make sure the right one matches the selector (as I show in the demo).
Demo: http://jsfiddle.net/ThinkingStiff/6ZUMa/
HTML:
Script: