Reputation: 713
Hello i have the following code jsfiddle. The add function works ok but the remove function doesn't work at all. Can you help me please solve the problem?
HTLM Part
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
</p>
</div>
Jquery Part:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').on('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
Upvotes: 1
Views: 1800
Reputation: 382454
A problem with $('#remScnt').on('click', function() {
is that you're trying to bind the event handler to the elements in the $('#remScnt')
collection, which is empty at that time.
Another problem is that only one element can have a given id, so you must use a class if you want to be able to add more than one line.
So I recommend this construct :
$('<p><label [...] class="remScnt" [...] ').appendTo(scntDiv);
...
$('#p_scents').on('click', '.remScnt', function() {
Upvotes: 5
Reputation: 276303
You are binding to an element before it is created. You need to do live monitoring:
$(document).on('click','#remScnt' ,function() {
Working fiddle: http://jsfiddle.net/basarat/gnQzk/
That said, I recommend using a class instead of id.
ie. something like :
$(document).on('click', '.remScnt', function() {
Upvotes: 1