I'm curious why when clicking on each input checkbox all the alerts are "_3" when I'm expecting "_0", "_1" and "_2" respectively. How would I go about getting the results I expect without much modification. This is to solve a much larger problem in a project I'm working on.
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="main"></div>
<script>
var generate = function()
{
var elem = document.getElementById('main');
var list = document.createElement('ul');
for(var i=0; i<3;i++)
{
var liElem = document.createElement('li');
var x = document.createElement('input');
x.setAttribute('type', 'checkbox');
x.setAttribute('value', i);
x.setAttribute('id', '_A' + i);
x.addEventListener('change', function () { alert('_'+(i)); });
liElem.appendChild(x);
list.appendChild(liElem);
}
elem.appendChild(list);
}
window.addEventListener('load', function () {
generate();
});
</script>
</body>
</html>
EDIT: found this as solution
x.addEventListener('change', function (i) { console.log('_'+i); }.bind(this, i));'