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.

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

3 Comments

Good description of why the asker was having the problem and how to solve it!
@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 :)
Thanks, from what I read about JS so far avoiding globals seems to be the best way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.