0

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?

3 Answers 3

3

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):
Sign up to request clarification or add additional context in comments.

Comments

1

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);

FIDDLE DEMO

1 Comment

With demo and even gave a good hint on "preventDefault" to disable submit action
0

yup!!! one way is to create a seperate function

$("#myForm").submit(callThis);

$("#mySelect").change(callThis);

function callThis(){
  alert("Same code here ...");
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.