0

I have many select all buttons within my HTML that essentially do the same thing. However they all have different ids because the buttons represent different divs that have different content within them. I am new to JS and I was wondering how can I perform the same logic across many select all buttons when one of them is clicked?

I thought about putting each select all button in an array containing all the ids and using

arr = [id1,id2,id3];

for (var i = 0; i < arr.length; i++) {
  var k = document.getElementById(arr[i]);
  k.onclick = function() {//...logic...}
}

I'm new to JS so I'm not sure if this is a good method to approach

Liondancer
  • 15,721
  • 51
  • 149
  • 255
  • Post a complete code example please. – j08691 Oct 28 '14 at 19:47
  • 2
    in jQuery you could use `$('#id1', '#id2', '#idn').click(function(){ alert("clicked") });` to achieve the desired result – pbaldauf Oct 28 '14 at 19:48
  • @pbaldauf hmmm i like that. Would there be something similar in vanilla JS? – Liondancer Oct 28 '14 at 19:49
  • 1
    No, listening on multiple elements is something unique to jQuery. CC @pbaldauf – Scimonster Oct 28 '14 at 19:54
  • 1
    You maybe could use a class instead of id's so that if you're adding a button you just have to give the same class for it to be handled. As you will probably have the same look for it, it will also be of use in your css. There is a getElementByClassName() method available in vanilla js. You just need to check for browser compatibility. – Laurent S. Oct 28 '14 at 19:55

1 Answers1

1

Your current code should work. Just make sure that in the array of IDs, they are proper strings (put quotes around them). Also, if you plan on doing something with i inside the click callback, please read How do JavaScript closures work?

Community
  • 1
  • 1
Scimonster
  • 32,893
  • 9
  • 77
  • 89