user3261158
user3261158

Reputation:

How to call the same function in two different ways?

I am trying to combine a function which will display alert (ofcourse I have a lot of code In this function but for this case It will be alert) after:

  1. Click on element with class .number
  2. Change select[name=receive]

I have this code but it doesn't work:

$(document).on(("click",".number"),("change","select[name=receive]"),function(){
    alert('test');
})

Upvotes: 1

Views: 93

Answers (5)

PeterKA
PeterKA

Reputation: 24638

Try this

function doMyWork() {
    console.lot( 'TEST' );
}
$('.number').on('click', doMyWork);
$('select[name=receive]').on('change', doMyWork);

Or, if your elements are inserted after DOM ready: You do not have to use this form if the target elements exist at DOM ready

function doMyWork() {
    console.lot( 'TEST' );
}
$(document).on('click', '.number', doMyWork)
.on('change', 'select[name=receive]', doMyWork);

Upvotes: 1

Spokey
Spokey

Reputation: 10994

You cannot separate events and selectors in a single .on() call. You have two options here. You can use them together....

$(document).on("click change", ".number, select[name=receive]"),function(){
    alert('test');
});

...however this means that .number will listen to both click and change, possible resulting in the function running 2 times.

You need to move the function outside and reuse it for every handler

var al = function(){
    alert('test');
};

$('.number').on('click', al);
$('select[name=receive]').on('change', al);

Upvotes: 1

epascarello
epascarello

Reputation: 207511

I am not sure where you learned that syntax, but that is not how on() works.

Use a named function and share it.

(function(){

   var shared = function(){
       console.log(this); 
   }

   $(document)
       .on("click",".number", shared)
       .on("change","select[name=receive]", shared);  

}());

Upvotes: 0

void
void

Reputation: 36703

$(document).on("click change",".number, select[name=receive]", function(){
    alert('test');
})

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try this

$(document).on("click change","select[name=receive], .number", function(){
    alert('test');
});

Or

var fn = function () {
   alert('test');
}

$(document).on("click", ".number", fn);
$(document).on("change", "select[name=receive]", fn); 

Upvotes: 1

Related Questions