0

When I click on the div element I want to alert the id of div I clicked on. But on all the div elements it is alerting the last value of array i.e. 'e1'.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body  onload="populate();">
    <script type="text/javascript">
    function populate() {

        var divArray = ["a1", "b1", "c1", "d1", "e1"];
        for (var x in divArray) {
            if (divArray[x] === 'a1')
                document.getElementById(divArray[x]).innerHTML = "aaaaa";
            else
                document.getElementById(divArray[x]).innerHTML = "Common";

            document.getElementById(divArray[x]).onclick = function() {
                getDiv(divArray[x]);
            };
        }
    }

    function getDiv(x)
    {
        alert(x);
    }

    </script>
    <div id="a1"></div>
    <div id="b1"></div>
    <div id="c1"></div>
    <div id="d1"></div>
    <div id="e1"></div>

</body>
</html>
  • 2
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – bfavaretto Jul 19 '13 at 20:15
  • also see: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Paul Jul 19 '13 at 20:18

4 Answers4

3

Your x is not the x you're hoping for. This might help.

// ...
document.getElementById(divArray[x]).onclick = (function(n) {
    return function() {
        getDiv(divArray[n]);
    };
}(x));
// ...
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • 1
    or he could just use bind, as in `.onclick = getDiv.bind(null, divArray[x]);` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Paul Jul 19 '13 at 20:23
1

Replace getDiv(divArray[x]) with getDiv(this.id), as you want to return the ID of the clicked element.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
0

This is because your for-loop has already ended by the time you actually click the div, so x is whatever it was when the loop ended. To fix this, you need to call getDiv(this.id);

Jordan
  • 1,433
  • 8
  • 14
0

Try passing the click event (e) into your click handler

        document.getElementById(divArray[x]).onclick = function(e) {
            console.log(e.toElement.id);
        };
kcathode
  • 94
  • 3