2014-09-28 103 views
0

eOk我使用此代碼添加和刪除輸入字段,但輸入字段的最大值未正確計數,問題出現在這一行$('。remove_field')。click(函數(e)。當我調用這行href tagets所有clasess具有相同的名稱,所以x--遞減的次數多於一次,例如,如果我有4個輸入x將被計算x-4。如何在簡單中解決這個問題方式。使用Jquery添加和刪除它後計算輸入字段

我試圖somethig這樣

$(#inp).on('click','.remove_field',function(e){}) 

,但它不工作對我嗎?任何解決方案

回答

0

您正在使用div標籤來代替,並最終在下面的語句div標籤:

$('#inp').append('<div><input class = "new_input" type=text name="name[]" placeholder="Unesite podatak"/><a class="remove_field "href="#"> X</a><div><br/>'); 

應該是:

$('#inp').append('<div><input class = "new_input" type=text name="name[]" placeholder="Unesite podatak"/><a class="remove_field "href="#"> X</a></div><br/>'); 
0

我沒有測試它,但剛剛從看看它,我可以看到你缺少}在你的if (x < max)聲明(右括號後x++;

0

發生什麼事是,每次點擊#add時,您都會爲所有現有輸入添加一個附加事件處理程序。因此,您可以在類remove_field上執行查詢,但僅請求最後一個。

$('.remove_field').last() 

JS小提琴:http://jsfiddle.net/timctran/j2oftq6v/

<div id="add">Click to Add an Input</div> 
<div id="inp"></div> 

<script> 
var max = 5; 
var x = 0; 

$('#add').click(function() { 
    if (x<5) { 
     $('#inp').append(' \ 
      <div> \ 
       <input class="new_input" type=text name="name"/> \ 
       <a class="remove_field" href="#"> X </a> \ 
      </div> \ 
     '); 
     x++; 
     $('.remove_field').last().click(function(e) { 
      $(this).parent('div').remove(); 
      x--; 
     }); 
    } 
}); 
</script> 
0

試試這個:

<script> 
$('document').ready(function() 
     { 
      var max = 5; 
      var x = 1; 

      $('#add').click(function(e) 
      { 
       if(x < max) 
       { 
        $('#inp').append('<div><input class = "new_input" type=text name="name[]" placeholder="Unesite podatak"/><a class="remove_field "href="#"> X</a><div><br/>'); 
        x++; 
      } 
      }); 
      $('.remove_field').click(function(e) 
      { 
       e.preventDefault(); 
       $(this).parent('div').remove(); 
      x--; 

      }); 

      $('body').on('click','.remove_field',function(e){ 

       $('div#inp')[0].childNodes[max-1].remove(); 
max = max-1; 
}); 
     }); 
</script> 

<button class="remove_field">remove</button> 
<button id="add">add</button> 
<div id="inp"> 
</div> 

但在這裏,我就刪除的每次點擊刪除最後一個字段。