javascript, 4 buttons and for-loop

Discussion in 'Programming' started by ja444, Mar 12, 2008.

  1. #1
    How can I get 4 buttons working with for loop? Each button should perform the same action, in this case the simple alert window

    here is the html code that I should get working:

    <html>
    <head>
    <title>untitled</title>
    <script type="text/javascript">
    window.onload = function HELLO(BUTTON1)
    {

    window.document.getElementById("BUTTON1").addEventListener("click", HELLO, false);
    alert("Hello world");
    }
    </script>
    </head>
    <body>

    <button id="BUTTON1">Hello World</button>

    <button id="BUTTON2">Hello World</button>

    <button id="BUTTON3">Hello World</button>

    <button id="BUTTON4">Hello World</button>

    </body>
    </html>
     
    ja444, Mar 12, 2008 IP
  2. Randombase

    Randombase Peon

    Messages:
    224
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #2
    for(variable = 1; variable <= 4; variable++)
    {
    window.document.getElementById("BUTTON1").addEventListener("click", HELLO, false);
    alert("Hello world");
    }
    
    Code (markup):
    Don't think I have a typo :)
     
    Randombase, Mar 12, 2008 IP
  3. vpguy

    vpguy Guest

    Messages:
    275
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Your code adds the event listener to the same button 4 times. I think the OP wanted to add an event listener to each button. The revised code would look like:
    for(variable = 1; variable <= 4; variable++)
    {
    window.document.getElementById[B]("BUTTON" + variable)[/B].addEventListener("click", HELLO, false);
    alert("Hello world");
    }
    
    Code (markup):
     
    vpguy, Mar 12, 2008 IP