2009-11-19 57 views
0

當單擊元素旁邊的按鈕時,我需要刪除一個表單元素。刪除選定的表單元素

$('#btnDel').click(function() { 

     var num = $('#input').prevAll().size(); 
     $('#form div:nth-child('+ num +')').remove(); 

     } 

似乎無法得到那個工作!非常感謝任何幫助。我覺得我只是選擇合適的元素迷茫......

編輯:有標記的要求:

<div id="form"> 
<form name="create" method="post" action="create.php"> 

    <input type="hidden" id="id" value="1"> 

    <label for="title">Title</label> 
    <input name="myusername" type="text" id="myusername"><br /><br /> 
    <div id="input" class="clonedInput"> 
     Question: <input type="text" name="question" id="question" /> 
     <input type="button" id="btnDel" value="Remove question" /> 
    </div> 
    <div> 
     <input type="button" id="btnAdd" value="Add another question" /> 
    </div> 
    <input type="submit" name="submit" value="Create survey"> 

</form> 

</div> 
+0

將真正幫助,如果你向我們展示的形式的HTML標記是什麼:) –

+0

是的,我們需要的標記。 – David

回答

0

的#btnDel表明您正在解決與ID = btnDel按鈕。如果是這種情況,應該只有一個按鈕,因爲每個ID都必須是唯一的。如果只有一個按鈕,則只需要在其旁邊需要移除一個元素。否則,您可以使用click函數的事件部分捕獲event.target,並相對於目標移除工作。

$(".btnDel").click(function(e){$(this).parent().remove()}); 
0

首先,你需要多刪除按鈕,以便給他們一個類,而不是一個id class="btnDel" 然後使用此代碼:

$(".btnDel").click(function(){ 
    $(this).closest("div").remove() 
}) 
+0

很好地工作,但只適用於第一個div? – Tom

0

我在你other question解決了這個問題有關刪除元素並改變計數。您需要的是每個問題的單個「添加問題」按鈕和「刪除問題」按鈕。然後每個問題和「刪除問題」按鈕需要分配一個類,而不是一個ID!

您可以在其他問題中使用我發佈的代碼(和工作示例),但實質上您需要使用刪除按鈕上的實時查詢,因爲它是動態添加的。

HTML

<div id="input" class="clonedInput"> 
Question: <input type="text" name="question" class="question" /> 
<input type="button" class="btnDel" value="Remove question" /> 
</div> 

腳本

$('.btnDel').live('click',function(){ 
$(this).parent().remove(); 
})