使用jquery删除动态创建的文本框

时间:2015-12-30 10:50:51

标签: jquery html textbox

我在点击按钮时动态创建文本框。我想知道用另一个按钮点击删除文本框。

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>');
       });

我这里有一个删除按钮。当我单击按钮时,我需要从相应的行中删除文本框。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

您将拥有许多包含相同ID Removebtnrow0screenNameTextBox等不正确的商品。改为使用类。

更改

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

和其他id类似的类:

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

然后,您将能够使用事件委派为所有这些按钮分配处理程序。例如,此代码将删除按钮单击时的整行:

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

这是working JSFiddle demo

如果您只想删除文本框,请使用:

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

答案 1 :(得分:0)

你可以这样做。希望这会对你有所帮助。

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

如果要删除完整的行,请使用$(this).closest('tr').remove()

答案 2 :(得分:0)

如果您只想删除文本框

%CPU