Reputation: 2279
I am running jQuery 1.9.1 and I want to trigger the same code on two events:
$("#myForm").submit(function() {
alert("Same code here ...");
});
$("#mySelect").change(function() {
alert("Same code here ...");
});
I were looking in to the "on" method but as far as I can see, it cannot trigger on two events with separate ID's?
Upvotes: 0
Views: 69
Reputation: 73906
Create a new function first like:
function myFunction() {
alert("Same code here ...");
}
and then pass the reference of the function to the jquery events like:
$('#myForm').submit(myFunction);
$('#mySelect').change(myFunction);
Upvotes: 1
Reputation: 36531
yup!!! one way is to create a seperate function
$("#myForm").submit(callThis);
$("#mySelect").change(callThis);
function callThis(){
alert("Same code here ...");
};
Upvotes: 0
Reputation: 388316
You need to write it as a separate function and register it with both the event handlers
function handler() {
alert("Same code here ...");
}
$("#myForm").submit(handler);
$("#mySelect").change(handler):
Upvotes: 3