One action on events for several buttons or controls with jQuery

There are 5 buttons on a page. If you click 1, 3 or 4 there must be one action, for 2 and 4 another one. You don’t have to write the same action for each control, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$(document).ready(function () { $('#button1').on('click', function () { console.log('good button clicked'); }); $('#button3').on('click', function () { console.log('good button clicked'); }); $('#button4').on('click', function () { console.log('good button clicked'); }); $('#button2').on('click', function () { console.log('wrong button clicked'); }); $('#button5').on('click', function () { console.log('wrong button clicked'); }); }); |
Of course, it’s not comfortable and compact record.
You can easily improve the code with 'add()' method.
1 2 3 4 5 6 7 8 |
$('#button1').add('#button3').add('#button4').on('click', function () { console.log('good button clicked'); }); $('#button2').add('#button5').add('#button5').on('click', function () { console.log('wrong button clicked'); }); |
There’s also another way to write the code, but it’s not universal. You can use it only when you know IDs of buttons.
1 2 3 4 |
$('#button1, #button3, #button4').on('click', function () { console.log('good button clicked'); }); |
With method ‘add()’ you can use variables to get controls.
1 2 3 4 5 6 7 8 |
$ctrl1 = $('#button1'); $ctrl2 = $('#button3'); $ctrl3 = $('#button4'); $ctrl1.add($ctrl2).add($ctrl3).on('click', function () { console.log('good button clicked'); }); |