0

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 the 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,

2 Answers 2

3

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 = [];
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

yes, thanks! if I were to wish to reset the form. So remove all except the original, easily possible?
0

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.

1 Comment

$('input[type="text"]:last').remove(); worked. Many thanks for putting me on right track.

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.