1

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.

cecilli0n
  • 449
  • 1
  • 9
  • 18

1 Answers1

4

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:

Community
  • 1
  • 1
p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
  • Good description of why the asker was having the problem and how to solve it! – Aheinlein Apr 23 '14 at 19:04
  • @cecilli0n Sorry, I should have been more clear. *Both* are closures, but the second has an IIFE around the variable, too. I've updated for clarity. Glad I could help :) – p.s.w.g Apr 23 '14 at 19:20
  • Thanks, from what I read about JS so far avoiding globals seems to be the best way to go. – cecilli0n Apr 23 '14 at 19:31