2014-09-10 26 views
0

我試圖通過添加和刪除輸入選項來動態構建input元素。 我也使用php從我的數據庫中動態構建下來。 當我添加輸入時,我痛苦數組中的父id,當我刪除輸入我使用拼接刪除它。我添加或刪除的每個框都包含幾個輸入jQuery store div parent id,並將其從數組中刪除

我將輸入成功添加到數組,併成功通過它們使用ajax,問題是當我刪除1輸入它刪除所有我的父母div如循環中。

var x = 1 
var appleTestList; 
var appleinputList = new Array(); 

$('#applePlus').click(function(e){ //on add input button click 
      var wrapper   = $("#appleDinamicBox"); //Fields wrapper 
      ; //initlal text box count 
      $.ajax({ 
      async: false, 
      type: "GET", 
      url: "sqlFunctrions.php", 
      data: 'func=dropDownbyValue&table=test&value=Test_ID&display=Test_Name&column=Test_Type&valueBy=Apple&selectName=appleTest&chooseFrom=Test', 
      success: function(msg){ 
       appleTestList=msg; 
      } 

     }); // Ajax Call 

      var htmlString=''; 

       x++; //text box increment 
       htmlString=htmlString + '<div class="seperate" id="'+x+'"><div class="col-lg-5"><label>Test Name:</label>'; 
       htmlString = htmlString + '<select name="appleTestName'+x+'" id="appleTestName'+x+'" class="form-control"><option value=\"0\">Test</option>' +appleTestList+'</select>'; 
       htmlString = htmlString + '</div><div class="col-lg-5"><label>Namber Of Setups</label><input class="form-control" type="text" name="appleNumOfSetups'+x+'" id="appleNumOfSetups'+x+'"></div><img src="images/minus-s.png" id="appleMinus" class="remove_field"></div>'; 
       $(wrapper).append(htmlString); //add input box    

       appleinputList.push(x); 

       $(wrapper).on("click",".remove_field", function(e){ //user click on remove text 
    e.preventDefault(); $(this).parent('div').remove(); 
    var id = $(this).parent().attr('id'); 
    alert(id); 
    appleinputList.splice(appleinputList.indexOf(parseInt(id)),1); 

      alert(id); 

}); 

} 

你可以我的錯誤,有任何其他的方式來做到這一點?

謝謝, Cfir。

+1

可能是這行:$(this).parent('div')。remove(); – DeFeNdog 2014-09-10 17:55:51

+0

我會在'.remove_field'元素中添加一個'data-targetid = x',並在處理程序中顯式地將其拉出('id = $(this).data('targetid')'),而不是使用父關係。 – Malk 2014-09-10 17:56:37

+0

你有沒有考慮過使用像Knockout這樣的模板庫來構建動態視圖?這是值得檢查:http://knockoutjs.com/ – masterwok 2014-09-10 17:58:47

回答

0

問題在於,每次單擊#applePlus(這會導致多個處理程序調用)時,綁定新的$(wrapper).on("click",".remove_field"處理程序。將此代碼移出#applePlus點擊處理程序。

Fiddle

$('#applePlus').click(function() 
{ 
    var wrapper = $("#appleDinamicBox"); //Fields wrapper 

    ... 

    appleinputList.push(x); 
}); 

$("#appleDinamicBox").on("click", ".remove_field", function(e){ //user click on remove text 
    e.preventDefault(); 
    $(this).parent('div').remove(); 
    var id = $(this).parent().attr('id'); 
    appleinputList.splice(appleinputList.indexOf(parseInt(id)),1); 
}); 
+0

謝謝,這正是答案:) – cfircoo 2014-09-10 18:22:34

+0

@cfircoo不客氣。 – Regent 2014-09-10 18:29:45

相關問題