2016-08-02 12 views
0

私は画像ごとにテーブル入力フォームを持っています。私は、ユーザーが最初の行(ホスト名、モデル、場所、購入、保証フィールド)だけを入力して、「Clone First Row」をヒットできるようにして、入力した内容を後続のすべての行にコピーします。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

返信とあなたの助けてくれてありがとう:)近くの点検で、あなたのスクリプトは、ちょうど私が予期した方法ではありません。まず、入力ボックスに現在フォーカスがあるものをクローンします。しかし、2つのドロップダウンをクローン化することはできないようです。私の理想的なシナリオは、クローンボタンを1回クリックするだけで、行全体を次のクローンにクローンすることでした。それは可能ですか? – daninthemix