开发者

Adding extra input fields when I need them

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


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" />');
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜