Reputation: 467
I am new to javascript, I have created 2 functions, createInput() which creates input boxes with a name parameter when called and appends them to a tag, newTwo() which calls createInput() twice with two different names.
I cannot seem to provide a index for the two name elements and make it increment each time the newTwo() is called. I need this so that I can trace the field values as a pair.
function createInput(name)
{
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", name);
var form = document.getElementById("foobar");
form.appendChild(input);
}
function newTwo()
{
var $i = 0;
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
}
When I call newTwo(), input fields are created with the array index as follows.
<input type="text" name="first_name[0]" />
<input type="text" name="last_name[0]" />
If I call it again, the next two fields will be
<input type="text" name="first_name[0]" />
<input type="text" name="last_name[0]" />
my desired output for the previous second call would be
<input type="text" name="first_name[1]" />
<input type="text" name="last_name[1]" />
Any suggestions? Thanks in advance.
Upvotes: 1
Views: 43
Reputation: 149000
Because you have var $i = 0;
inside the function, you're creating a new variable and initializing it to 0
every time you run the function. If you want to use a variable that maintains its value between function calls, you need to declare it outside the function. For example:
var $i = 0;
function newTwo()
{
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
}
Or if you really want to avoid making $i
global you could create a IIFE around it like this:
var newTwo = (function() {
var $i = 0;
return function() {
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
};
})();
Note that there are subtle differences between this and the previous version. See these questions for more details:
Upvotes: 4