3

I have number of different buttons on my website and I want to assign different task to each button, currently I am referencing them one by one using getElementByID and because I have so many buttons I ended up writing endless lines of codes just to reference the buttons, having some knowledge of java I understand that what I have done could be achieved with less code using for loop but I am not quite sure how to go about doing that, any help is welcomed.

Currently this is how I am referencing my buttons:

    var Button1Menu = document.getElementById("button1menu"); 
    var Button2Menu = document.getElementById("button2menu"); 
    var Button3Menu = document.getElementById("button3menu"); 
    var Button4Menu = document.getElementById("button4menu"); 
    var Button5Menu = document.getElementById("button5menu"); 
    var Button6Menu = document.getElementById("button6menu"); 
    var Button7Menu = document.getElementById("button7menu"); 
    var Button8Menu = document.getElementById("button8menu"); 
    var Button9Menu = document.getElementById("button9menu"); 
    .....
    .....
    .....
    var Button43Menu = document.getElementById("button43menu"); 

and then I am assigning click listener to each one:

Button1Menu.onclick = function() {

     //doing something

  };

Is there a better way of achieving this please.

7
  • 2
    use event delegation Commented Feb 23, 2016 at 10:51
  • How is "Doing something" differing depending on the clicked button? Commented Feb 23, 2016 at 10:54
  • Hi @Teemu what do you mean? Commented Feb 23, 2016 at 11:03
  • Hi @RajaSekar please can you show me an example. Commented Feb 23, 2016 at 11:04
  • What is the difference between the click handlers of the buttons? Are they totally diffrerent, or are they mostly doing the same task, just having some slightly varying part? Commented Feb 23, 2016 at 11:13

6 Answers 6

4

initiate a counter and keep checking till you get a button that doesn't exist

var counter = 1;
var button  = document.getElementById( "button" + counter + "menu" );

while ( button )
{
   button.addEventListener("click", function(){
      //do something here
   });

   button  = document.getElementById( "button" + ( ++counter ) + "menu" );
}

if all the buttons needs to be assigned a click event then

var buttons = document.querySelectorAll( "button[id^='button'][id$='menu']" );
for ( var counter = 0; counter < buttons.length; counter++)
{
    buttons[counter].addEventListener("click", function(){
      //do something here
   });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Just a suggestion: What about querySelectorAll ?
@RayonDabre OP has not mentioned that he wants to assign click event to all the buttons on his page, just to the ones which are id'd like this. Anyways, will add that solution as well.
@Teemu oh, thanks for pointing out. changed counter++ to ++counter.
Not my down vote, but the first snippet attaches two handlers to the first button. Also, the question is not clear, all the handlers aren't necessarily the same (they might be though).
@Teemu actually now he has mentioned in his comment that buttons may do different things. Which actually tells me that OP is not clear on what he/she is looking for. Why would be making 43 buttons on a page and doing different stuff for each of them? Only possible reason for having so many buttons could be for a grid to have a button for each line item.
|
3
$('button').on('click',function(){
    alert($(this).attr('id'));
});

Now inside the click event use the $(this) jquery object

Comments

1

Please, try this (added function doSomething(item) to explain a real usage):

    function doSomething(item) {
        switch (item.id) {
            case 'button3menu': 
                // Make this button do something, only it. For example: 
                alert('Hey, you are pressing me!');
                break;
            default:
                // Make all the button's whose id is not contemplated as a case value 
                alert('My id is: ' + item.id);
                break;
    }}

        <script>
        (function()
        {
            var num = 4;
            for (var i = 0; i < num; i++)
            {
                var elem = document.createElement('button');
                elem.id = "button" + i + "menu";
                elem.innerHTML = "button" + i;
                document.body.appendChild(elem)

                elem.addEventListener('click', function(){doSomething(this)});
            }
        })()
        </script>

Comments

1

Assuming that you have a parent element for all or some of your buttons:

<div id="parent">
<button id="button1menu">button</button>
<button id="button2menu">button</button>
<button id="button3menu">button</button>
<button id="button4menu">button</button>
<button id="button5menu">button</button>
<button id="button6menu">button</button>
</div>

A single click event listener is enough to handle all of them:

document.getElementById("parent").addEventListener("click", function(e) {
     // e.target is the clicked element
    //check if button1menu has been clicked
    if(e.target && e.target.id == "button1menu") {
        alert(e.target.id + " was clicked");
    }

    //check if button2menu has been clicked
    if(e.target && e.target.id == "button2menu") {
        alert(e.target.id + " was clicked");
    }

  //etc
 });

You can experiment more in this fiddle

This is called event delegation and its good for you

Comments

0

jQuery solution

$("button[id^='button']").on('click', function() {
  console.log($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1menu">button</button>
<button id="button2menu">button</button>
<button id="button3menu">button</button>
<button id="button4menu">button</button>
<button id="button5menu">button</button>
<button id="button6menu">button</button>

1 Comment

Nick, OP hasn't used jquery tag in his OP.
0

If someone still looking for solution - create collection using document.querySelectorAll, and then via loop assign index for every button. After that you can put in each case functionality that you need. It works for simple tasks.

For example below, i have three buttons, by clicking any of them background color will change:

HTML:

<div id="page-container">
  <button type="button" class="btn btn-red">red</button>
  <button type="button" class="btn btn-green">green</button>
  <button type="button" class="btn btn-blue">blue</button>
  <script src="buttonCollection.js"></script>
</div>

JS:

let pageContainer = document.getElementById('page-container')
let buttons = document.querySelectorAll('.btn')
let index = undefined;

for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function () {
    index = i;
    switch (index) {
        case 0:
          pageContainer.style.backgroundColor = "red"; 
          break;
      
        case 1:
          pageContainer.style.backgroundColor = "green";
          break;
      
        case 2:
          pageContainer.style.backgroundColor = "blue";
          break;
      
        default:
          pageContainer.style.backgroundColor = "bisque";
          break;
      }
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.