-5

I have a set of buttons with ids "del1", "del2", and so on. I'm trying to make an onclick function that fires when any of those buttons are clicked on. So basically replace:

$(document).on('click', '#del1', function(e) {
    alert("For button1");
});

$(document).on('click', '#del2', function(e) {
     alert("For button2");
});

etc

With a single function. The amount of buttons can change, and there's no limit to the amount of buttons. How can I do this?

bongwater
  • 1
  • 4
  • Hello @bongwater, can you add html code to your post? – Merci Dieu KIMPOLO Feb 03 '20 at 17:51
  • Or like any of the other hundreds of question on ["how to find elements whose id starts with ..."](https://www.google.com/search?q=jquery+id+starts+with+site%3Astackoverflow.com) – Andreas Feb 03 '20 at 17:57
  • Just add a class to all delete buttons and add click event to all: https://stackoverflow.com/questions/5563783/jquery-class-click-multiple-elements-click-event-once – An Illusion Feb 03 '20 at 17:59

2 Answers2

2

Method 1:

$('[id^="del"]').click(function() { //ID begins with "del"
    //code here
}); 

//or

$(document).on('click', '[id^="del"]', function(e) {
     //code here
});

Method 2: Add a common class to all your buttons:

$('.myButton').click(function(){/*code..*/});
Marcelo The Mage Coder
  • 1,944
  • 2
  • 11
  • 29
0

You can give a class name to all elements and attach an event handler for that

<button data-index="1" class="button">click here</button>
<button data-index="2" class="button">click here</button>
<button data-index="3" class="button">click here</button>
<button data-index="4" class="button">click here</button>
<button data-index="5" class="button">click here</button>

$(document).on('click', '.button', function(e) {
alert("For button"+$(this).data('index'));});
Beingnin
  • 2,288
  • 1
  • 21
  • 37
  • you need to share why the down vote is for – Beingnin Feb 03 '20 at 17:57
  • The idea of the question was to use something that all elements already have in common to make a single handler to all of then (the starts with part of the id attribute...). To add a class name in all elements is, on my point view, a "work around", a way to not deal with the main point of the question. Besides that, it also adds unnecessary code to the html. – Caio Sant'Anna Feb 03 '20 at 18:12
  • 1
    @CaioSant'AnnaI don't think using class is a work around that we do in a daily basis and we even do not know whether the OP using ids coz he is not aware of the usage of classes. and the accepted answer even has a second solution , which uses class – Beingnin Feb 03 '20 at 18:16