0

I am using jquery , in my project i have same action for form submit and for hyperlink click event. Code is same for both action , but i need to write separate event handler as follows

$("#elem1").click( //do some action ) and

  $("#form1").submit(//do some action )

can we write mixed event handler for both in one line ?

0

2 Answers 2

4

Just create a function and pass it as a reference to your handlers:

function myHandler(event) {
  //do some action
};

$('#elem1').on('click', myHandler);
$('#form1').on('submit', myHandler);
Sign up to request clarification or add additional context in comments.

2 Comments

can also modify selector to include both elements: $('#elem1, #form1').on('click', myHandler);
That wouldn't work unless you wanted to trigger the handler every time the form was clicked. It would be possible to write a single handler for $('#elem1, #form1').on('click submit', myHandler);, but your handler would need to check if the event were a click and which element was clicked, which would be much more complicated that the two lines above.
2

Use .trigger to call the other event's code:

$("#form1").submit(function() { /* do some action */ } );
$("#elem1").click(function() { $('#form1').trigger('submit'); } );

However, if #elem1 is the submit button for #form1, you don't need to do this, as it will run the code twice in a row.

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.