2014-01-07 40 views
0

我想只添加兩行。我有兩個問題,下面的代碼。jquery使用綁定添加和刪除輸入

  1. 它正在添加兩個以上的行。
  2. 當我嘗試刪除它不會刪除選定的記錄。

http://jsfiddle.net/5WwTB/14/這是DEMO

$('#addProfile').bind('click', function() { 

      if($('#container').find('#removeProfile').length < 2) { 

       var len = $('#container').find('#removeProfile').length; 
       //alert(len); 
       var index = len+1; 

       $('#container').append('<div>&nbsp;</div><div class ="form-group-inline"><label class="col-sm-2 control-label" >Profile Number</label><div class="col-sm-3"><input class="text-input form-control" type="text" name="profileNumber" id="profileNumber" /></div><label class="col-sm-2 control-label" >Amount</label><div class="col-sm-3"><input class="text-input form-control" type="text" name="amount" id="amount" /></div><div class="col-sm-2"><button type="button" id="removeProfile" class="btn btn-success">RemoveProfile</button></div></div>'); 


      }else{ 

       bootbox.alert("You cannot add more than two profiles!", function() {}); 

      } 
     }) 
}); 

    $('body').on('click', '#removeProfile', function() { 
if($('#container').find('#removeProfile').length > 0) {    
    $(this).parent().remove(); 

} 
}) 

我能在我的工作區添加記錄,但相同的代碼沒有在撥弄工作。我希望有人可以幫助我首先讓它在小提琴中工作,然後看看我擁有的問題。謝謝!

+0

不知道你的HTML看起來像什麼,但看到你的代碼讓我覺得它是無效的,因爲你不能有多個ID爲ID的元素** removeProfile **。這也是你的問題。嘗試獲取具有相同ID的元素的長度時,'.length'將始終返回1。 – putvande

+0

我只有一個ID與「removeProfile」。這是容器附加上面的代碼。 – user3067524

+0

不,當您單擊時,您正在附加一個新的。 – putvande

回答

0

當你做$('#container').find('#removeProfile').length,你總是會得到0或1,而不是更多。
無論如何你都不能有兩次相同的ID。刪除ID或使其唯一。 (http://msdn.microsoft.com/en-us/library/ie/ms534704(v=vs.85).aspx)。您可以使用.form-group-inline來檢查您有多少人。 所以做:

if($('#container .form-group-inline').length < 2) { .... } 

而對於刪除的部分,要添加一個單擊處理程序的元素與選擇name=removeProfile。你沒有。相反:

$('body').on('click', '.form-group-inline .btn-success', function() { 
    if($('#container .form-group-inline').length > 0) {    
     $(this).parents('.form-group-inline').remove(); 
    } 
} 

這應該工作。

+0

Iwill試試這個,與此同時我更新了我的原始文章,使用id而不是名字。這將工作刪除部分? – user3067524

+0

我試過了。添加部分正在工作。它能夠計數和提醒。但刪除部分仍然無法正常工作。 – user3067524

+0

它和你的代碼一樣,只有一個不同的選擇器。也許你需要刪除父母的父母..不適當更新答案。 – putvande