2016-08-02 80 views
0

我有一个表格输入形式,根据图片。我希望用户能够输入第一行(主机名,型号,位置,购买的,保修字段),然后点击“克隆第一行”,并将所输入的内容复制到所有后续行中。jQuery克隆表行(DATA)

如何最好的在jQuery中做到这一点?在PHP中生成

该行与此代码,并且都具有唯一的ID:

<?php for($t = 1; $t <= 20; $t++){ ?> 
     <tr> 
      <td><input type="text" name="hostname-<?=$t;?>" class="form-control" id="hostname-<?=$t;?>"></td> 
      <td><input type="text" name="asset-tag-<?=$t;?>" class="form-control" id="asset-tag-<?=$t;?>"></td> 
      <td><input type="text" name="serial-<?=$t;?>" class="form-control" id="serial-<?=$t;?>"></td> 

Table

回答

2

$("button").on("click", function() { 
 
    var firstRow = $("table").find("tr:first-child"), 
 
     rowsToModify = firstRow.nextAll(); 
 
     
 
    firstRow.find(":input").each(function(idx) { 
 
     rowsToModify.find(":input:eq(" + idx + ")").val(this.value); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td><input type="text" name="hostname-0" class="form-control" id="hostname-0"></td> 
 
     <td><input type="text" name="asset-tag-0" class="form-control" id="asset-tag-0"></td> 
 
     <td><input type="text" name="serial-0" class="form-control" id="serial-0"></td> 
 
     <td> 
 
     <select name="state-0" class="form-control" id="state-0"> 
 
      <option>Open</option> 
 
      <option>Waiting</option> 
 
      <option>Closed</option> 
 
     </select> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td><input type="text" name="hostname-1" class="form-control" id="hostname-1"></td> 
 
     <td><input type="text" name="asset-tag-1" class="form-control" id="asset-tag-1"></td> 
 
     <td><input type="text" name="serial-1" class="form-control" id="serial-1"></td> 
 
     <td> 
 
     <select name="state-1" class="form-control" id="state-1"> 
 
      <option>Open</option> 
 
      <option>Waiting</option> 
 
      <option>Closed</option> 
 
     </select> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td><input type="text" name="hostname-2" class="form-control" id="hostname-2"></td> 
 
     <td><input type="text" name="asset-tag-2" class="form-control" id="asset-tag-2"></td> 
 
     <td><input type="text" name="serial-2" class="form-control" id="serial-2"></td> 
 
     <td> 
 
     <select name="state-2" class="form-control" id="state-2"> 
 
      <option>Open</option> 
 
      <option>Waiting</option> 
 
      <option>Closed</option> 
 
     </select> 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table> 
 
<button type="button">Clone values from first row</button>

+0

不能得到这个工作。我的按钮现在是:'' – daninthemix

+0

显示的脚本不是火警或遗忘解决方案:)您是否更改过选择器得到正确的'

+0

感谢您的回复和您的帮助:)仔细检查您的脚本确实能够正常工作,但效果并不像我预期的那样。首先,它将克隆当前所关注的任何输入框。但是,它似乎无法克隆两个下拉列表。我的理想场景是单击克隆按钮将整行克隆到下一个。那可能吗? – daninthemix