2014-09-28 85 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> 

但在这里,我就删除的每次点击删除最后一个字段。