Reputation: 575
I have implemented a dynamic adding removing text boxes using a post i found in net. I succesfully added dynamic text boxes but removing them is not working. Please see my design and jquery
<td style="font-size: large; vertical-align:top" >
Mobile:
</td>
<td valign="top" >
<div id="divAdd">
<p>
<asp:TextBox ID="txtMobile" runat="server" Width="120px"></asp:TextBox>
<asp:ImageButton ID="add" runat="server" ValidationGroup="r"
ImageUrl="~/img/add.png" Height="16px" Width="16px" />
</p>
</div>
and my script is:
$(function () {
var addDiv = $('#divAdd');
var i = $('#divAdd p').size() + 1;
$('#add').on('click', function () {
$('<p><input type="text" size="100" id="p_new" name="p_new_' + i + '"/><a href="#" id="remove">Remove</a></p>').appendTo(addDiv);
i++;
return false;
});
$('#remove').on('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
and also the size of the dynamic text boxes i am creating are not changing if i change the size property why is that?
Upvotes: 1
Views: 84
Reputation: 2094
Since Content is dynamic, You Have to Delegate click event for the removal button
Try this
$('body').on('click','#remove','',function(e){
e.preventDefault();
if (i > 2) {
$(this).parents('p').remove();
i--;
}
});
Upvotes: 1
Reputation: 62488
try this:
$(function () {
var addDiv = $('#divAdd');
var i = $('#divAdd p').size() + 1;
$('#add').on('click', function () {
$('<p><input type="text" size="100" id="p_new" name="p_new_' + i + '"/><a href="#" id="remove">Remove</a></p>').appendTo(addDiv);
i++;
return false;
});
$(document).on('click','#remove', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
Here is Fiddle DEMO
Upvotes: 1
Reputation: 43481
Try changing to $(document).on('click', '#remove', function(){})
. on
has to be binded to static elements in DOM to work properly.
Upvotes: 5