Reputation: 1458
I know this is very easy to others. I just need a opinion how can I loop in cell value in every row? Because I created a option to create another input or row. I tried this but only get the first cell per row.
for (var i = 1; i<table.rows.length; i++)
{
alert(table.rows[i].cells[0].children[0].value);
}
$(document).ready(function() {
$("#addMore").click(function() {
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function() {
if ($('#customFields tbody tr').length == 1) {
alert('Error');
} else {
$('#customFields tr:last').remove();
}
});
});
function myFunction() {
var table = document.getElementById("customFields");
for (var i = 1; i < table.rows.length; i++) {
alert(table.rows[i].cells[0].children[0].value);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-md-12">
<table class="table" id="customFields">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Nick Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary" id="addMore">+ Add</button>
<button type="submit" class="btn btn-danger" id="removeRow">- Remove</button>
<a href="javascript:myFunction()">Run</a>
</div>
Upvotes: 2
Views: 59
Reputation: 178285
You use jQuery - why not continue?
$(function() {
$("#run").on("click",function(e) {
e.preventDefault();
$("#customFields > tbody > tr > td > input").each(function() {
// or $("#customFields tbody").find("input").each...
console.log($(this).val());
});
});
});
and change to buttons and give the link an ID
<button type="button" class="btn btn-primary" id="addMore">+ Add</button>
<button type="button" class="btn btn-danger" id="removeRow">- Remove</button>
<a href="#" id="run">Run</a>
Upvotes: 1