Problem removing input from form after adding
so I have got my form successfully adding a new input on the click of a button. However now I want to be able to remove that last addition on the click of a new button and then also feature a reset button.
this was the code I had in place, which I realise now just removes th开发者_如何转开发e submit button first, which obviously I dont want.
here is my javascript snippet: (note ive included the appendTo() to demonstrate the div I am successfully appending to)
$(function() {
var i = $('input').size('#temp') + 1;
$('a#add').click(function() {
$('<input type="text" value="user' + i + '" />').appendTo('#temp');
i++;
});
$('a#remove').click(function() {
if(i > 3) {
$('input:last').remove();
i--;
}
});
many thanks,
Your script will remove the last input from the page, not the last one from the div with id temp. Maybe you are removing another input from your page.
Try this:
$('a#remove').click(function() {
if(i > 3) {
$('#temp input:last').remove();
i--;
}
});
Edit:
You only close the $('a#remove').click()
event handler, not the anonymous function. That may be a copy/paste error here, but may also be a problem in your code.
Edit 2:
To remove all but the original, I would recommend keeping a reference to all added inputs, as this reduces the need to traverse the DOM for each remove. So do something like this (This code is neither tested nor verified):
$(function() {
var addedInputs = [];
$('a#add').click(function() {
var newInput = $('<input type="text" value="user' + i + '" ">').appendTo('#temp');
addedInputs.push(newInput);
});
$('a#remove').click(function() {
var inputToRemove = addedInputs.pop();
inputToRemove.remove();
});
$('a#clear').click(function() {
var i,
inputToRemove;
for(i = addedInputs.length - 1;i >= 0; i -=1) {
inputToRemove = addedInputs[i];
inputToRemove.remove();
}
addedInputs = [];
});
});
Have you tried :
$("a#remove").click(function() {
if(i > 3) {
$("input[type='text']").last().remove();
i--;
}
});
This will select the inputs having type="text", take the last one and remove it.
精彩评论