2017-10-06 81 views
-1

使用jQuery,我有一個按鈕,它爲點擊添加輸入字段,每個字段由函數和計數器變量var count = 0;確定,每個字段爲idname。如何重置計數器的形式提交到數據庫後,使輸入字段的idname從默認無需再次刷新頁面開始?成功提交到數據庫後,將函數變量重置爲默認值

這裏是形式的一個片段:

$(document).ready(function() { 
 
     var wrapper = $(".input_fields_wrap"); 
 
     var count = 0; 
 

 
     $('p#add_field').click(function(e) { 
 
      e.preventDefault(); 
 
      count += 1; 
 
      $('#container').append(
 
       '<div>\n\ 
 
        <label>Weight</label><input type="text" id="weight_' + count + '" name="weight[]' + '"/>\n\ 
 
       <a href="#" class="remove_field" id="removebtn">Remove</a><br>' 
 
      ); 
 
     }); 
 

 
     $(wrapper).on("click", ".remove_field", function(e) { 
 
      e.preventDefault(); 
 
      $(this).parent('div').remove(); 
 
      x--; 
 
     }) 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form action="" method="POST" id="productForm"> 
 
    <div id="container" class="input_fields_wrap"> 
 
     <div> 
 
     <p id="add_field"><button type="button" href="#"><span>Add new</span></button></p> 
 
     </div> 
 
    </div> 
 
    <button type="submit" name="btnSubmit">Save to database</button> 
 
</form>

這是我一直在努力與成功後提交移除動態元素。 (我是否以正確的方式做這件事?)現在我怎麼能在這裏重置var count= 0?提前致謝。

$.ajax({ 
     url: form.attr('action'), 
     type: form.attr('method'), 
     data: form.serialize(), 
     dataType: 'json', 
     success: function(response) { 

      if (response.success == true) { 
      $("[id*='weight']").each(function() { 
       $(this).parent("div").remove(); 
      }); 

      $("[id*='removebtn']").each(function() { 
       $(this).parent("div").remove(); 
      }); 
+1

數= 0應該工作...只要確定它的範圍 – Salketer

+1

'$( 「#集裝箱」)。子女()是可用的。未來().remove()'會比當前要做的更簡單。但是......我認爲你甚至不需要'count' var或id。 –

+0

如果確實需要枚舉它們,則可以在提交表單時這樣做,因此不需要重新設置計數變量。 –

回答

0

您的代碼看起來像這樣

$(document).ready(function() { 
     var wrapper = $(".input_fields_wrap"); 
     var count = 0; 

     $('p#add_field').click(function(e) { 
      e.preventDefault(); 
      count += 1; 
      $('#container').append(
       '<div>\n\ 
        <label>Weight</label><input type="text" id="weight_' + count + '" name="weight[]' + '"/>\n\ 
       <a href="#" class="remove_field" id="removebtn">Remove</a><br>' 
      ); 
     }); 

     $(wrapper).on("click", ".remove_field", function(e) { 
      e.preventDefault(); 
      $(this).parent('div').remove(); 
      x--; 
     }) 
//Send data to database on a click of a button 

$('#sendDataTodb').click(function(){ 
$.ajax({ 
     url: form.attr('action'), 
     type: form.attr('method'), 
     data: form.serialize(), 
     dataType: 'json', 
     success: function(response) { 

      if (response.success == true) { 
      $("[id*='weight']").each(function() { 
       $(this).parent("div").remove(); 
      }); 

      $("[id*='removebtn']").each(function() { 
       $(this).parent("div").remove(); 
       }); 
} 
}); 
    //reset counter 
    count =0; 
    }); 

    });