Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event listener for multiple elements - jQuery

In the ASP MVC page I'm currently working on, the values of three input fields determine the value of a fourth. Zip code, state code, and something else called a Chanel Code will determine what the value of the fourth field, called the Territory Code, will be.

I just started learning jQuery a couple weeks ago, so I would first think you could put a .change event that checks for values in the other two fields and, if they exists, call a separate method that compares the three and determines the Territory code. However, I'm wondering if there is a more elegant way to approach this since it seems like writing a lot of the same code in different places.

like image 393
NealR Avatar asked Apr 29 '13 19:04

NealR


2 Answers

You can bind a callback to multiple elements by specifying multiple selectors:

$(".field1, .field2, .field3").click(function() {
    return field1 +
           field2 + 
           field3;
});

If you need to perform specific actions depending on which element was clicked, another option would be to create a function which performs the actual computation and then invoke that from each callback.

var calculate = function() {
    return field1 +
           field2 + 
           field3;
};

And then invoke this function when on each click:

$(".field1").click(function() {
    // Perform field1-specific logic
    calculate();
});

$(".field2").click(function() {
    // Perform field2-specific logic
    calculate();
});

// etc..

This means that you do not repeat yourself.

like image 116
alexn Avatar answered Oct 03 '22 00:10

alexn


This works for me

jQuery(document).on('scroll', ['body', window, 'html', document], 
    function(){
        console.log('multiple')
    }
);
like image 5
Dũng Trần Trung Avatar answered Oct 02 '22 23:10

Dũng Trần Trung