KTM
KTM

Reputation: 868

How to attach different events on multiple selectors through .on function in jquery?

I have two elements as following on my page:

<input type="text" id="textfield"/>  
<input type="button" id="button" value="CLICK"/>

And in my Javascript code I have the following:

$(document).ready(function() {  
     $("#button,#textfield").on("click change",function() {
           // This won't work because I don't need click function 
           // to be worked on the text field 
     });
});

What I need is click function to be worked on button and need only change function to be worked on text field. How do I do this?

Upvotes: 1

Views: 558

Answers (6)

jfriend00
jfriend00

Reputation: 707168

If you want the same code to be called for different events on different objects, you can put the event handling code into a common function and then specify the exact conditions in each event registration:

$(document).ready(function(){  
    function myEventHandler(e) {
        // your code here
    }

    $("#button").on("click", myEventHandler);
    $("#textfield").on("change", myEventHandler);
});

Upvotes: 3

Dineshkani
Dineshkani

Reputation: 3005

Try using like this if you want only one .on function

$("#button,#textfield").on("click change",function(){
 if ($(this).attr('type') == "text"){
       alert("Do your change function");
 }
 else if ($(this).attr('type') == "button"){
    alert("Do your click function");
 }
});

See Demo

Upvotes: 0

Svetoslav
Svetoslav

Reputation: 4676

Try:

$(document).ready(function(){  
     $("#textfield").on("change",function(e){
         my_function(e);
     });

     $("#button").on("click",function(e){
         my_function(e);
     });

     function my_function(e){
        // e = event...
        // your actions...
     }
});

Upvotes: 0

Emery King
Emery King

Reputation: 3534

Assign them separately:

$('#button').click(function(){
    //button code here
});

$('#textfield').change(function(){
    // text field code here
});

If you want them to do the same thing, create a separate function:

function doSomething() {
    // text field and button code here
}

and then reference that function instead:

.click(doSomething);
...
.change(doSomething);

Also, i should tell you, "change" does not do what you would think for a text field. It does not fire while typing, only when you "blur" the text field after updating it. It's more for checkboxes and things of that nature. I would use .keyup()

Upvotes: 0

Eli
Eli

Reputation: 14827

Seperate to two function:

 $("#button").on("click change",function(){
     // Handle button
 });

 $("#textfield").on("change",function(){
     // Handle Textfield
 });

Upvotes: 0

von v.
von v.

Reputation: 17108

Split your code into:

$(document).ready(function(){  
     $("#button").on("click",function(){

     });
     $("#textfield").on("change",function(){

     });
});

Why did you put them together?

Upvotes: 0

Related Questions