Multiple item event listener - jQuery

On the ASP MVC page I'm working on now, the values ​​of the three input fields determine the value of the fourth. The zip code, status code, and something else called the Chanel Code will determine what the value of the fourth field, called the Territorial Code, will mean.

I just started learning jQuery a couple of weeks ago, so at first I thought you could put a .change event that checks the values ​​in two other fields and, if they exist, calls a separate method that compares three and determines the territory code. However, I am wondering if there is a more elegant way to approach this, since it seems that a lot of the same code has been written in different places.

+6
source share
2 answers

You can associate a callback with several elements by specifying several selectors:

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

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

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

And then call this function when on every click:

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

This means that you are not repeating yourself.

+14
source

This works for me jQuery(document).on('scroll',['body', window, 'html', document], function(){console.log('multiple')});

+1
source

Source: https://habr.com/ru/post/943908/


All Articles