Master Detail Table
by Hifni Nazeer
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<div class="form-row">
<div class="col">
<div class="form-group">
<label>Year 1</label>
<div class="form-row">
<div class="col">
<input type="text"/>
</div>
<div class="col">
<input type="text"/>
</div>
</div>
</div>
</div>
<div class="col">
<div class="form-group">
<label>Year 2</label>
<div class="form-row">
<div class="col">
<input type="text"/>
</div>
<div class="col">
<input type="text"/>
</div>
</div>
</div>
</div>
<div class="col">
<div class="form-group">
<label>Year 3</label>
<div class="form-row">
<div class="col">
<input type="text"/>
</div>
<div class="col">
<input type="text"/>
</div>
</div>
</div>
</div>
</div>
<table class='table' id='table'>
<thead>
<tr>
<th>Order No</th>
<th>Description</th>
<th><button id="AddOrder">Add Order</button></th>
</tr>
</thead>
<tbody id="tableBody">
<tr id="Order-1">
<td>
<input type="text" name="Order1.Id" value="1" />
</td>
<td>
<input type="text" name="Order1.Desc" value="This is an Order" />
</td>
<td>
<button type="button" data-id="1" class="removeOrderBtn">Remove</button>
</td>
</tr>
</tbody>
</table>
<input type="hidden" id="count" value="1">
JavaScript
$(document).ready(function() {
$("#AddOrder").on('click', function(e) {
//get the counter input and store it because we're going to update the value later.
var table = $('#table');
var rows = table.find('tr');
var rowOuterHtml = rows[rows.length-1].outerHTML;
var lastRowIdx = $("#count");
var counter = lastRowIdx.val();
counter++;
//Assumed your new order description has an id of description.
var description = "Halo"
//Again you need to prepare your html so that the model binding will work by forming the name correctly.
var newRow = "<tr id='Order-" + counter + "'>"+
"<td><input type='text' name='Orders[" + counter + "].OrderId' value='" + counter + "' /></td>"+
"<td><input type='text' name='Orders[" + counter + "].OrderDesc' value=" + description + "/></td>"+
"<td><button type='button' data-id='" + counter + "' class='removeOrderBtn'>Remove</button></td>"+
"</tr>";
var tableBody = $("#tableBody");
//Append the new tr to the table body after the other rows (might be a better way to do this with append or something similar).
tableBody[0].innerHTML = tableBody[0].innerHTML + newRow;
//Update the counter stored in the input so that we can keep track of how many items we have in the list to try avoid duplicate numbers
$('#count').val(counter);
});
$(".removeOrderBtn").on('click', function(e) {
console.log('clicked');
var button = $(e.relatedTarget);
var id = button.data('id');
console.log(id);
var tableBody = $("#tableBody");
tableBody.remove("#Order-" + id); // I think this takes a selector.
var counterInput = $("#count");
var counter = counterInput.val();
counter--;
counterInput.val(counter);
});
});