0

Suppose to have more buttons:

<input type="button" id="number_1" value="A">
<input type="button" id="number_2" value="B">

<input type="button" id="number_n" value="N">

I want get click when the user click on them. So I would use something like this code (without Jquery):

var button=document.getElementById('[id^=number]');
button.onclick=function(){alert("HIII")};

But this code is not work. Anyone can help?

Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
Polly
  • 459
  • 1
  • 9
  • 22

2 Answers2

1
'[id^=number]'

That's an attribute selector, not an ID and not a regular expression. You shouldn't pass it to getElementById.

You can use selectors with querySelectorAll

var buttons = document.querySelectorAll('[id^=number]');

but that returns a NodeList, not a single element, so you have to loop over it:

for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.onclick=function(){alert("HIII")};
}

and there is no point in creating a new function each time you go around the loop, create one and reuse it:

for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.onclick = myFunction;
}    

function myFunction () { 
    alert("HIII");
}
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

Attribute selectors

document.querySelectorAll()

Array.prototype.forEach()

Function.prototype.call()

EventTarget.addEventListener()

Array.prototype.forEach.call(document.querySelectorAll('[id^=number_]'), function (element) {
  element.addEventListener('click', function (e) {
   alert(e.target.id);
  });
});
<input type="button" id="number_1" value="A">
<input type="button" id="number_2" value="B">
<input type="button" id="number_n" value="N">
Alan Larimer
  • 584
  • 7
  • 24