views:

87

answers:

2

I trying to create an HTML/CSS/JavaScript based list manager.

I'm using text input fields as my individual list items, with the first text input field being:

<input type="text" id="input1" value="Enter your first item" />

I'm using jQuery to create a new text input field if I've used the previous text input field:

<input type="text" id="input2" value="Add another item" />

The jQuery code checks if the value of the first text input field has changed, and then creates the second text input field.

If the value of the second text input field changes, then I want a third text input field to be created:

<input type="text" id="input3" value="Add another item" />

I use jQuery to keep track of the ids of each text input field, and to manage the creation of new ones. However, it only creates a new text input field only if the first text input field, input1, changes. I want it to create a new text input field if the last text input field changes. This is the code I use to create the new text input field:

oldNum = newNum;
newNum++;
var newElement = $("#input" + oldNum).clone().attr('id', 'input' + newNum).attr('value', 'Add another item');
$("input").last().after(newElement);

Thanks in advance for your help.

R

+1  A: 

You can use jQuery's live function to only handle the change event for the last input, like this:

$('input:last-child').live('change', function() {
    $(this).after('<input id="input' + ++newNum + '" value="Add another item" />');
});
SLaks
A: 

You may want to look at utilizing the .one() event binding syntax. It executes an action at most one time, so you can attach it to each input field as it is created.

var current = 1;
$("input1").one("change",createNextInput);

function createNextInput()
{
    var next = current + 1;
    var newElement = $("input"+current).clone().attr({id: "input"+next,value: "Add another item"});
    $("input"+current).after(newElement);
    $("input"+next).one("change",createNextInput);
    current++;
}

You could probably optimize that some, but you get the idea.

ckramer