-4

When I click on a button, I want to get the id of the button that was clicked. How can I do that with JavaScript?

For example:

<input type="button" id="1" class="buttonID" value="answer" onClick=myFunction() />
<input type="button" id="2" class="buttonID" value="answer" onClick=myFunction() />
<input type="button" id="3" class="buttonID" value="answer" onClick=myFunction() />
Joshua
  • 648
  • 7
  • 18
khassepaz
  • 45
  • 1
  • 7

4 Answers4

-1
 This will alert "clicked" when a button with id my-button is clicked:

    HTML



 <button id="buttonID">Click me</button>

    JavaScript

    var el = document.getElementById("buttonID");

    if (el.addEventListener) {
        el.addEventListener("click", function() {
            alert("Clicked " + el.id);
        }, false);
    } else { //IE8 support
        el.attachEvent("onclick", function() { 
            alert("Clicked " + el.id);
        });
    }
shv22
  • 680
  • 5
  • 28
-1

You can assign the button to a variable, and then target the ID of the button through that variable.

var button = document.getElementById('myButton');

button.onclick = function() {
    alert(button.id);
}
Joshua
  • 648
  • 7
  • 18
-1

The function passed to the onclick event receives an 'event' object in the scope. You can access it's target element, and then the id

window.myFunction = function() {
    console.log(event.target.id)
}
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
-1

You need to define function in your header (or JS file call in your header) otherwise this function will be undefined onclick event and you need to add 'this' param to function (for binding clicked element), like this:

<script>
function myFunction(e){
  alert(e.id);
}
</script>

<input type="button" id="1" class="buttonID" value="answer" onClick=myFunction(this) />
<input type="button" id="2" class="buttonID" value="answer" onClick=myFunction(this) />
<input type="button" id="3" class="buttonID" value="answer" onClick=myFunction(this) />

Here is code on JsFiddle: https://jsfiddle.net/kv8y4q24/

Štefan Ondáš
  • 358
  • 1
  • 5
  • 18