1

I have created 4 buttons and every button with its own id and I have a function that displays the given element id. so I want to apply it on all this 4 buttons. what did I do wrong?

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>

<script type="text/javascript">
    
function show_id(element){
    alert(element.id)
}

for(i=0; i!=document.getElementsByTagName('button');i++){

    target = document.getElementsByTagName('button')[i]
    target.onclick = show_id(target)

}

</script>
</body>
</html>

8
  • I think it would be better to use class instead of id. Commented Dec 24, 2020 at 9:41
  • would it make any different ? Commented Dec 24, 2020 at 9:42
  • 2
    You probably meant i!=document.getElementsByTagName('button').length. As it stands, you're comparing a number to an HTMLCollection, potentially creating an infinite loop, only stopped by the error it creates inside the loop. Commented Dec 24, 2020 at 9:42
  • i've changed it, now they all alert the last button id ! Commented Dec 24, 2020 at 9:44
  • 1
    wait so you would like that the button which was pressed do the alert? Commented Dec 24, 2020 at 9:50

4 Answers 4

1

Do it as below -

function show_id() {
  alert(this.id)
}

var buttons = document.querySelectorAll("button");

for (var i = 0; i < buttons.length; i++) {
  buttons[i].onclick = show_id;
}
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>

Passing arguments to onclick event -

Using HTML -

function show(element, value) {
  console.log(element.id);
  console.log(value);
}
<button id='b1' onclick='show(this, "a")'>Click</button>

Using JS -

function show(value, event) {
 console.log(value);
 console.log(event.target.id);
}

var button = document.getElementById("b1");

button.onclick = show.bind(this, "a");
<button id='b1'>Click</button>

But, as mentioned by @connexo, use addEventListener to bind DOM events.

Sign up to request clarification or add additional context in comments.

7 Comments

is it necessary to write (element) after the function ?
@badr, No, not required. I have removed it.
i want to know how to use a function with arguments in "onclick" Attribute
I really recommend you stop using index-based loops, the var keyword (unless you know exactly why you are using it over const or let) and also element.onevent-properties. Use the DOM API which offers element.addEventListener(eventName, handlerFunction).
@connexo, Agreed! I tried to stick to the original code posted by the poster for the sake of the problem faced.
|
1

Here's how you would do this in modern JS:

for (const button of document.querySelectorAll('button'))
  button.addEventListener('click', function() { console.log(this.id) })
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>

Explanation:

When you register a regular function() as an event listener and it gets executed because the event occurs, the this keyword inside the function will point to the element that the listener was registered on.

2 Comments

Btw, I haven't used a single index-based for-loop in the past 3 years, and I do web development as a professional on a daily basis. I recommend you dig into forEach and for...of loops.
i will do that, Thanks For Helping
0

Okay, update the code to use with querySelectorAll and forEach, might help you to understand.

document.querySelectorAll('button').forEach((button)=>{
  button.addEventListener('click', function(){
   console.log(this.id);
  });
});
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>

2 Comments

Usage of inline event listeners is really bad coding practice, please don't suggest that to someone that has already passed that stage of noob coding.
i want to use a function with arguments in the "onclick" that's what i want to know how
-1

You can get your button elements length and iterate through your buttons.

I would recommend creating a class for something like this, so instead of just take all buttons give the buttons you would like to involve in this the same class.

Here is a way you can do it.

    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <body>

    <button id='b1' class="btnWithID">Click</button>
    <button id='b2' class="btnWithID">Click</button>
    <button id='b3' class="btnWithID">Click</button>
    <button id='b4' class="btnWithID">Click</button>

    <script type="text/javascript">
        
    function show_id(){
        alert(this.id)
    }


    let btns = document.querySelectorAll('.btnWithID');
    for(i=0; i < btns.length ;i++){

        btns[i].onclick = show_id;

    }


    </script>



    </body>
    </html>

5 Comments

when i run it it alerts all the classes but nothing shows when i click them
Sorry with the argumentation it will applied to all of the 4 buttons I was a bit missleaded. I have updated my answer now
someone already wrote the same answer, but thanks anyways.
and there's no need for a class i think, you can just querySelectorAll('button') or getElementByTagName('button')
Probably you dont want to call that function for every button on your site just for a specific amount of buttons. Thats why I would recommend to use classes.

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.