Search code examples
javascripthtmlclickwindows-8.1dom-events

How to get a button's ID when clicked in Windows 8 apps?


I'm trying to get the ID of the button I clicked but I can't do it. I tried everything but it doesn't work.

How can I do this? It saves the last value which is resetBttn


Solution

  • This works on an ordinary webpage:

    var update = function(el) {
      document.getElementById("msg").innerHTML = el.id;
    }
    <button onclick="update(this)" id="btn1">btn1</button>
    <button onclick="update(this)" id="btn2">btn2</button>
    <span id="msg">ID goes here</span>

    But it's better to use event listeners:

    var update = function(el) {
      document.getElementById("msg").innerHTML = el.id;
    }
    
    document.getElementById("btn1").addEventListener("click", function() {
      update(this);
    });
    
    document.getElementById("btn2").addEventListener("click", function() {
      update(this);
    });
    <button id="btn1">btn1</button>
    <button id="btn2">btn2</button>
    <span id="msg">ID goes here</span>

    That second method also works with Windows 8.1 apps.