Reputation: 843
$(document).ready(function() {
var n=1;
$("#add").click(function(){
if(n<8){
$("#form").append("
<input type='text' name='input_" + (n++) +"'/>
<input type='button' id='remove_" + (n++) +"' value='REMOVE'/>");
}
});
});
I have a Jquery add input text.
How can I remove the specific input.
Upvotes: 3
Views: 7051
Reputation: 44740
Use class for your button like this -
$("#form").append("<input type='text' name='input_" + (n++) +"'/><input type='button' class='remove' value='REMOVE'/>");
And to remove input and button -
$('form').on('click','.remove',function(){
$(this).prev('input').remove();
$(this).remove();
n--;
});
Demo ---->
http://jsfiddle.net/JvW3L/4/
Upvotes: 1
Reputation: 73896
Try this:
$("#form").on("click", "input[id^='remove_']", function () {
$(this).prev(':text').remove();
$(this).remove();
n--;
});
Since the inputs
are added dynamically, you need to use event delegation to register the event handler.
WORKING FIDDLE
Upvotes: 1
Reputation: 253308
Assuming an element with the id
of 'deleteInput' is to be clicked to trigger the deletion:
$('#deleteInput').click(function(e){
// in case it's an element with a default action:
e.preventDefault();
$('#form input').last().remove();
n--;
});
The above will simply remove the last input
element added, and decrement the n
variable.
If, on the other hand, you want to remove a specific input
, other than the last:
$('.deleteInput').click(function(e){
e.preventDefault();
$(this).prev('input').remove();
});
This assumes that the element, with a class of deleteInput
will immediately follow the input
to be removed. In this case I'm leaving n
as-is, and leaving you to find some way of re-using the vacated/emptied 'slot' for the input
to be recreated (since a simple decrement would probably cause two elements to (invalidly) share the same id
.
References:
Upvotes: 5
Reputation: 2216
You have to select an element, using jquery selectors. After you have selected it, you can do various things, one of them is removing it.
You can select elements by name, attribute, type, it's position in DOM or id.
In your case, the simplest would be, for input of id "input_3":
$("#input_3").remove();
Upvotes: 0
Reputation: 27802
How about this:
$("#remove_").remove();
(Assuming that you want to remove the second input with id='remove_'
)
Upvotes: 0