2016-08-03 44 views
1

我正在使用jquery動態添加新錶行。它成功添加,現在我想根據下拉值動態拉動每條記錄並顯示在多個div中。所有工作正常,如果錶行只有一個,但是當我使用jquery添加新行時,它不會引起計數器值由於這個,當我從seconf行選擇下拉值時,它不會將記錄與它對齊。添加新字段時生成動態值

function add_allowance() { 

    var click = 2; 
    jQuery("#addrows").click(function(){ 
     jQuery('#maintable tr:last').after('<tr class="tablechild"><td><select name="empallownacename" id="allowancename" class="select2_category form-control"><option value="none" selected="selected">-Select-</option></select></td><td><input type="text" name="empmount" value="" class="form-control" /></td><td><input type="text" name="empdescription" value="" class="form-control" /></td><td><a style="cursor: pointer;" value="Remove" class="minusbtn" id="remove"><i class="fa fa-trash-o"></i></a></td></tr>'); 
    }); 
    click++; 
} 



    <tr class="tablechild"> 
    <td> 
     <select name="allowancename<?php echo $counter; ?>" id="allowancename" class="select2_category form-control"> 
      <option>-Select-</option> 
      <?php foreach($allowances as $allowance):?> 
      <option value="<?php echo $allowance['id']; ?>"><?php echo $allowance['name'];?></option> 
       <?php $counter; ?> 
      <?php endforeach; ?> 
     </select> 
    </td> 
    <td><input type="text" id="allowanceamount" name="allowanceamount" value="" class="form-control" /></td> 
    <td><input type="text" id="allowancedesc" name="allowancedesc" value="" class="form-control" /></td> 
    <td> 
     <a style="cursor: pointer;" value="Remove" class="minusbtn" id="remove"><i class="fa fa-trash-o"></i></a> 
    </td> 
</tr> 

回答

0

當你點擊時,該方法被調用,它始終將變量初始化爲2。這不是很好的做法。你可以這樣做: function add_allowance(){

var click; 
    jQuery("#addrows").click(function(){ 
     jQuery('#maintable tr:last').after('<tr class="tablechild"><td><select name="empallownacename" id="allowancename" class="select2_category form-control"><option value="none" selected="selected">-Select-</option></select></td><td><input type="text" name="empmount" value="" class="form-control" /></td><td><input type="text" name="empdescription" value="" class="form-control" /></td><td><a style="cursor: pointer;" value="Remove" class="minusbtn" id="remove"><i class="fa fa-trash-o"></i></a></td></tr>'); 
    }); 
    click=$('table tr).length; // It will count number of rows in the table and return integer value no of rows 
}