Reputation: 2570
I have a table input form as per the picture. I want users to be able to enter just the first row (hostname, model, location, purchased, warranty fields) and then be able to hit 'Clone First Row' and it copies what they've entered to all the subsequent rows.
How best to do this in jQuery?
The rows are being generated in PHP with this code, and all have unique IDs:
<?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>
Upvotes: 0
Views: 1025
Reputation: 21911
$("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>
Upvotes: 2