0

Is it possible to use multiple selectors and multiple events in jQuery?

I want to combine the following:

$('#submit-modal').click(function() {
$('#modal-form').submit(function() {

Into something like (or similar):

$('#submit-modal, #modal-form').on('click', 'submit', function() {

I've tried this, but it is not working.

Update (more of what I'm looking to accomplish):

$('#submit-modal').click().$('#modal-form').submit(function() {

I only want the click() attached to the #submit-modal and submit() attached to the #modal-form but if either is initiated it runs the same function.

3
  • 2
    Separate the events by a space instead of a comma like 'click submit' Commented Sep 25, 2013 at 1:49
  • Not hard... $('#submit-modal, #modal-form').on('click submit', function() { Commented Sep 25, 2013 at 1:52
  • Thanks! That did it, but not the result I am looking for. Because now when I click anywhere in the form it submits. Any way around this? Commented Sep 25, 2013 at 2:07

3 Answers 3

1

The solution here is to trigger the form submission from the click event so that the code related to form submission is present only in one palce.

$('#submit-modal').click(function() {
    $('#modal-form').submit();// $('#modal-form')[0].submit();
});
$('#modal-form').submit(function() {
    //do the submit code here
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this:

$("#submit-modal, #modal-form").on("click submit", function() {..});

This made that the anonimous function executes when you click or submit in #submit-modal or #modal-form

2 Comments

Thanks, that does work but my logic was messed up because now when I click anywhere in the form it submits. Any way to prevent that?
Yes, separating the calling function of click and submit. When you attach the event click to a element of the DOM, it execute when you click in everywhere of this element. Answering your new cuestion of the update, you looking something like: var myfunction = function () {...} $("#submit-modal").on("click", myfunction); $("#modal-form").on("submit", myfunction);
0

Yah, you might better off keeping each event with each selector, unless they trigger by the same event.

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.