2016-07-28 92 views
1

我需要添加通過jQuery刪除已添加的文本框, 添加輸入文本工作正常,但是當我刪除它,它不刪除。 這裏是我的代碼:任何想法?jQuery的刪除添加輸入文本

jQuery代碼

$(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><div class="container"><div class="row"><div class="col-lg-3"><input type="text" name="mytime[]" class="form-control input-sm"/></div><div class="col-lg-3"><input type="text" name="mytext[]" class="form-control" /></div><div class="col-lg-3"><a href="#" class="remove_field">Remove</a></div></div></div></div>'); //add input box 
      } 
     }); 

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

HTML代碼:

<div class="input_fields_wrap"> 
       </div> 

回答

1

的一點是:

$(this).closest('div.container').remove(); 

$(this).parent('div').remove(); 

更改此行帶

從jQuery的:

.closest(選擇)

對於組中的每一個元素,獲得通過自身測試元素,並通過其祖先向上遍歷DOM樹的選擇相匹配的第一個元素。

的片段:

$(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><div class="container"><div class="row"><div class="col-lg-3"><input type="text" name="mytime[]" class="form-control input-sm"/></div><div class="col-lg-3"><input type="text" name="mytext[]" class="form-control" /></div><div class="col-lg-3"><a href="#" class="remove_field">Remove</a></div></div></div></div>'); //add input box 
 
    } 
 
    }); 
 

 
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text 
 
    e.preventDefault(); 
 
    $(this).closest('div.container').remove(); 
 
    x--; 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button class="add_field_button">Add input field</button> 
 
<div class="input_fields_wrap"> 
 
</div>

+0

你好,這得益於工作,但如何 「最接近」 的作品? –

+1

@MartneyAcha最接近查找第一個根元素。雖然父母得到第一父節點,父母最近返回所有的家長節點停止與指定選擇的第一個父。 – gaetanoM