The variable i is always going to evaluate to 11. The for loop will run every time you run that function, and will set the name attribute of your input element to "name0", "name1", "name2", "name3", "name4", "name5", "name6", "name7", "name8", "name9", "name10", and finally... "name11". What you probably want to do is set up a closure to store the value, unless you want to use another attribute on an html element to store the value. My solution is pretty similar to MDN's information on closures here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Here's what I came up with. Probably more efficient to set a value on an html element and increment that...
<button onclick="afunction()">Insert New Text Field</button>
<script>
function counter() {
var i = 0;
return {
increment: function () {
i++;
},
value: function () {
return i;
}
};
}
var i = counter();
function afunction() {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", "something cool");
i.increment();
x.setAttribute("name","input"+i.value());
document.body.appendChild(x);
}
</script>
http://codepen.io/IAMZERG/pen/VjLJwO