Milos Nikolic Milos Nikolic - 4 months ago 6
Javascript Question

Return button id on click - JavaScript

I am making a program that is supposed to make a column of buttons on load.
After that, on click, it should make new column of buttons and display id of the button that is clicked.

It works fine when it is supposed to make new column of buttons, but it displays id of every button in the column. It even returns me ids of the next column. Ids of the first button columns are displayed on load.

Can someone help me to make it display just the id of the button that is clicked.
Here is the code:

<html> <head>
<style>
.addItem {
width: 80px;
float: left;} </style>
<script>
var lev = 0; var levmax=5;var some;

function addBu(){
repeat();
};

function repeat(){
if(lev<levmax){
lev++;
var bo = document.getElementById("kod");
var di = document.createElement('DIV');
di.className="addItem";
for (var i=0; i<4; i++){
var bu= document.createElement('BUTTON');
var te = document.createTextNode('Text');
var te1 = document.createTextNode(lev.toString());
var br = document.createElement('BR');
bu.id=(lev*10+i).toString();
some=(lev*10+i).toString();
bu.addEventListener("click", repeat);
bu.addEventListener("click" , reply_clickk(some));
bu.appendChild(te);
bu.appendChild(te1);
di.appendChild(bu);
di.appendChild(br);
}
bo.insertBefore(di, bo.childNodes[0]);
}

function reply_clickk(clicked_id){
alert(clicked_id);
};

};
</script>
</head>
<body id="kod" onload="addBu()">
</body></html>

Answer

The problem is you call the event handler and attach its return value to the click event instead of the function.

bu.addEventListener("click" , reply_clickk(some));  

you probably rather want something like this

bu.addEventListener("click" , function(e){reply_clickk(e.target.id)});

In addition your some variable is global; change it to var some to be scoped to your function repeat

var some=(lev*10+i).toString();  

See the JSFiddle