2016-08-02 36 views
1

我如何設法刪除最後的<div><input type="text" name="mytext[]"></div>即使是從「頂部」按鈕刪除?當我創建很多字段時,當我單擊「刪除它們頂部的圖形」時,它會刪除所有字段,而不是最後一個字段。使用jQuery刪除動態列表中的最後一個輸入字段

當我點擊按鈕場上的收屍時,我作出新的領域它消除了場,但我想也刪除,並從最上面的扣子

<div class="input_fields_wrap"> 
    <button class="add_field_button"> 
     <span class="glyphicon glyphicon-plus"></span> 
    </button> 
    <button class="remove_field" ><span class="glyphicon glyphicon-trash"></span> 
    </button> 
    <div><input type="text" name="mytext[]"></div> 
</div> 
$(document).ready(function() { 
    var max_fields = 10; //maximum input boxes allowed 
    var wrapper = $(".input_fields_wrap"); //Fields wrapper 
    var add_button = $(".add_field_button"); //Add button ID 
    var x = 1; //initlal text box count 
    $(add_button).click(function (e) { //on add input button click 
     e.preventDefault(); 
     if (x < max_fields) { //max input box allowed 
      x++; //text box increment 
      $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">\n\ 
           <button ><span class="glyphicon glyphicon-trash"></button>\n\ 
           </span></a></div>'); //add input box 
     } 
    }); 
    $(wrapper).on("click", ".remove_field", function (e) { //user click on remove glyphicon 
     e.preventDefault(); 
     $(this).parent('div').remove(); 
     x--; 
    }) 
}); 

回答

2

爲了解決這可以使用nextAll('div:last')。試試這個:

$wrapper.on("click", ".remove_field", function(e) { //user click on remove glyphicon 
    e.preventDefault(); 
    $(this).nextAll('div:last').remove(); 
    x--; 
}) 

Working example

注意,我修改了JS稍微讓你不雙包裝你的jQuery對象,我也修改了HTML稍微所以,很明顯這是即使不使用圖標也可以添加/刪除按鈕。

+0

謝謝你的回答:) – RosS

0

你應該找到這個父母的最後一個孩子並將其刪除。

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove glyphicon 
    e.preventDefault(); 
    $(this).parent().children('div:last-child').remove(); 
    x--; 
}) 
相關問題