How To Attach Different Events On Multiple Selectors Through .on Function In Jquery?
I have two elements as following on my page: And in my Javascript code I have th
Solution 1:
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(){
functionmyEventHandler(e) {
// your code here
}
$("#button").on("click", myEventHandler);
$("#textfield").on("change", myEventHandler);
});
Solution 2:
Split your code into:
$(document).ready(function(){
$("#button").on("click",function(){
});
$("#textfield").on("change",function(){
});
});
Why did you put them together?
Solution 3:
Seperate to two function:
$("#button").on("click change",function(){
// Handle button
});
$("#textfield").on("change",function(){
// Handle Textfield
});
Solution 4:
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()
Solution 5:
Try:
$(document).ready(function(){
$("#textfield").on("change",function(e){
my_function(e);
});
$("#button").on("click",function(e){
my_function(e);
});
functionmy_function(e){
// e = event...// your actions...
}
});
Post a Comment for "How To Attach Different Events On Multiple Selectors Through .on Function In Jquery?"