Unnikrishnan.S
Unnikrishnan.S

Reputation: 185

Remove dynamically created textboxes using jquery

I am creating textboxes dynamically on button click. I want to know to remove textboxes with another button click.

HTML

<table class="table-fill tbfill">
    <thead>
       <tr>
         <th class="text-left" runat="server">Screen Name</th>
         <th class="text-left" runat="server">Seats Available</th>
         <th class="text-left"></th>
       </tr> 
    </thead>
   </table>
<input id="btnAdd" type="button" value="ADD"/>

jQuery

$("#btnAdd").bind("click", function ()
       {
        $("tbody.addScreen").append('<tr id="row0">' +
            '<td class="text-left" name="screenName"> <input id="screenNameTextBox"/> </td>' +
            '<td class="text-left"> <input id="seatsAvlTextBox" name="seatsAvl" /> </td>' +
            '<td class="text-left"> <input type="button" value="Remove" id=Removebtn/> </td>' +
            '</tr>');
       });

I have a Remove button here. When I click the button I need to remove the textboxes from the corresponding row. How can I do this?

Upvotes: 1

Views: 1272

Answers (3)

Hemal
Hemal

Reputation: 3760

If you want to remove only textboxes

$(document).on('click', '.RemoveBtn', function() {
    $(this).closest('tr').find("input:text").remove();
});

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You will have many items with the same ids Removebtn, row0, screenNameTextBox etc. which is incorrect. Use classes instead.

Change

<input type="button" value="Remove" id=Removebtn/>

and other ids to similar classes:

<input type="button" value="Remove" class="RemoveBtn"/>

Then, you will be able to use event delegation to assign a handler for all these buttons. For example, this code will remove the whole row on button click:

$(document).on('click', '.RemoveBtn', function() {
    $(this).closest('tr').remove();
});

Here is the working JSFiddle demo.

If you want to remove textboxes only, then use:

$(document).on('click', '.RemoveBtn', function() {
    $(this).closest('tr').find('input[type="text"]').remove();
});

Upvotes: 2

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can do it like following. Hope this will help you.

$('.tbfill').on('click', '#RemoveBtn', function() {
    $(this).closest('tr').find('input').remove();        
})

Use $(this).closest('tr').remove() if you want to remove complete row.

Upvotes: 0

Related Questions