How to get data in an Editable Table to send via AJAX? - javascript

I have a modal and there is an Dynamic Editable table. I am seeking a way of getting the data of the editable table to the JS variables. Then I can pass these data to the controller via AJAX. I tried so many codes. but I couldn't find the suitable way. How should I get values to variables ?
Form blade
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="opening_invoice_table_body">
<tr>
<td><input type="date" class="form-control form-control-alternative date" name="opening_invoice[1][date]"></td>
<td><input type="text" class="form-control form-control-alternative detail" name="opening_invoice[1][detail]"></td>
<td><input type="text" class="form-control form-control-alternative invoice-no" name="opening_invoice[1][invoice_no]"></td>
<td><input type="number" class="form-control form-control-alternative amount" name="opening_invoice[1][amount]" min="0" step="any" placeholder="0.00"></td>
<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success"><i class="fas fa-download"></i> Save</button>
<button type="reset" class="btn btn-success"><i class="fas fa-eraser"></i> Clear</button>
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="fa fa-window-close"></i> Close</button>
</div>
</div>
</form>
Script
<script>
$(document).ready(function(){
var counter = 2;
//add rows
$("#add_row").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="date" class="form-control form-control-alternative date" name="opening_invoice[' + counter + '][date]"></td>';
cols += '<td><input type="text" class="form-control form-control-alternative detail" name="opening_invoice[' + counter + '][detail]"></td>';
cols += '<td><input type="text" class="form-control form-control-alternative invoice-no" name="opening_invoice[' + counter + '][invoice_no]"></td>';
cols += '<td><input type="number" class="form-control form-control-alternative amount" name="opening_invoice[' + counter + '][amount]" min="0" step="any" placeholder="0.00"></td>';
cols += '<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>';
newRow.append(cols);
$("#opening_invoice_table").append(newRow);
counter++;
});
//delete rows
$("#opening_invoice_table").on("click", "#delete_row", function (event) {
$(this).closest("tr").remove();
counter -= 1
counter++
});
});
//calculate total amount
$("#opening_invoice_table").on('input', '.amount', function () {
var calculated_total_sum = 0;
$("#opening_invoice_table .amount").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_amount").val(calculated_total_sum);
});
function newOpeningInvoice() {
var e = window.event || arguments.callee.caller.arguments[0];
e.preventDefault();
//Here I want to get table data. Below variables used for just testing purpose.
//var date = +$('.amount').val();
// var detail = $("input[class='detail']").val();
// var invoice_no = +$('.detail-no').val();
// var amount = +$('.amount').val();
// var date = "2020-03-27";
// var detail ="value";
//alert(amount);
$.ajax({
url: "opening_invoice/create",
type: "POST",
data: {'date': date, 'detail': detail, 'invoice_no': invoice_no, 'amount': amount, '_token':'{{csrf_token()}}' },
success: function (data) {
$('#add_opening_invoice_modal').modal('hide');
swal({
title: "Success!",
text: "Opening Invoice Saved Successfully!",
type: "success",
showConfirmButton: false,
timer: 1500,
});
}
});
return false;
}
</script>

Okey well I think this code might help you a lot.
I recommend you to create the "dynamic" parts in the javascript itself. This way you can use the data easier in my opinion. Here is how:
Javascript:
//To use them globally in the script. NOTE: Needs to be above the onload, otherwise javascript does not know the elements yet.
let trElement;
let tdElement;
let inputElement;
window.onload = onload();
function onload() {
//Create elements
trElement = document.createElement("tr");
tdElement = document.createElement("td");
inputElement = document.createElement("input");
//Set elements parameters
inputElement.type = "date";
inputElement.classList.add("form-control", "form-control-alternative", "date");
inputElement.name = "opening_invoice[1][date]";
//Appends
tdElement.append(inputElement);
trElement.append(tdElement);
document.getElementById("opening_invoice_table_body").appendChild(trElement);
//I do not have jQuery installed but you should create them like this:
// let inputElement = $('<input/>', {
// 'class': 'form-control form-control-alternative date'
// 'name': ...
// });
}
function createPartOfATable() {
console.log(inputElement.value);
}
HTML:
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
//This part has changed. Removed the HTML inside this tbody since I create it in javascript.
<tbody id="opening_invoice_table_body"></tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row" onclick="createPartOfATable();"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
Keep in mind that I created it in pure Javascript since I did not have jQuery installed at the moment. But I wrote some examples on how you should do it. Also jQuery documentation gives you a lot of info to do it with jQuery.

I could find the answer and it is working fine. serialize() is used to send the array of dynamic table data via AJAX to the controller.
//add rows
$('#add_row').on('click', function () {
var tr = '<tr>'+
'<td><input type="date" class="form-control form-control-alternative date" name="date[]"></td>'+
'<td><input type="text" class="form-control form-control-alternative detail" name="detail[]"></td>'+
'<td><input type="text" class="form-control form-control-alternative invoice-no" name="invoice_no[]"></td>'+
'<td><input type="number" class="form-control form-control-alternative amount" name="amount[]" min="0" step="any" placeholder="0.00"></td>'+
'<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>'+
'<tr>';
$('tbody').append(tr);
});
//delete rows
$('#opening_invoice_table').on('click', '#delete_row', function (event) {
var last=$('tbody tr').length;
if(last==1){
//do nothing
} else {
$(this).parent().parent().remove();
}
});
//calculate total amount
$("#opening_invoice_table").on('input', '.amount', function () {
var calculated_total_sum = 0;
$("#opening_invoice_table .amount").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_amount").val(calculated_total_sum);
});
});
//submit opening invoice data
$('#opening_invoice_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"opening_invoice/create",
method:'post',
data:$(this).serialize(),
dataType:'json',
success:function(data)
{
$('#add_opening_invoice_modal').modal('hide');
swal({
title: "Success!",
text: "Opening Invoice Saved Successfully!",
type: "success",
showConfirmButton: false,
timer: 1500,
});
}
})
});
<form id="opening_invoice_form">
#csrf
<div class="modal-body">
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" class="form-control form-control-alternative date" name="date[]"></td>
<td><input type="text" class="form-control form-control-alternative detail" name="detail[]"></td>
<td><input type="text" class="form-control form-control-alternative invoice-no" name="invoice_no[]"></td>
<td><input type="number" class="form-control form-control-alternative amount" name="amount[]" min="0" step="any" placeholder="0.00"></td>
<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success" id="sad"><i class="fas fa-download"></i> Save</button>
<button type="reset" class="btn btn-success"><i class="fas fa-eraser"></i> Clear</button>
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="fa fa-window-close"></i> Close</button>
</div>
</div>
</form>

Related

How to display the dynamic table data to another table using javascript

Iam trying to display multiple products to upload at once by using add product button, it displays the entire table to enter the product details. Here Iam facing the issue with add column option.
When I click on add grade option, columns are added successfully for one product, but if it comes for multiple products it will added to every table. So this is the 1st issue.
And secondly whatever the codes are entered in dynamic table were affected to packing list table.
Here is the code which I have tried.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> -->
<style type="text/css">
input[type=text] {
width: 150px;
}
.form-group{
padding-bottom: 30px;
}
</style>
<style type="text/css">
.table-content {
padding: 20px;
}
.remove {
margin-left: 10px;
color: red;
}
.remove:hover {
cursor: pointer;
}
.form-control {
width: 90px;
}
</style>
<script>
$(document).ready(function(){
var max=2;
var x = 1;
$("#add_product").click(function(){
var html = '<div class="table-content"><div style="padding-bottom: 20px;"><button type="button" class="btn btn-primary add-row" style="margin-right: 10px;">Add Codes</button><button type="button" class="btn btn-info add-col">Add Grades</button></div><table class="table table-bordered table-hover table-sortable"><thead><tr><tr><th></th><th colspan="3" class="text-center">CODES</th><th class="text-center">GRADES</th></tr><tr><th>Delete code</th><th class="text-center">CODES</th><th class="text-center">PRODUCTION</th><th class="text-center">REGN NO</th><th class="text-center"><select name="grade1" id="grade1" class="form-control"><option value="0">Select</option><option value="13/15">13/15</option><option value="16/20">16/20</option><option value="21/25">21/25</option><option value="26/30">26/30</option><option value="31/40">31/40</option><option value="41/50">41/50</option><option value="51/60">51/60</option><option value="61/70">61/70</option><option value="71/90">71/90</option><option value="91/110">91/110</option></select></th><th id="total">TOTAL</th></tr></tr></thead><tbody><tr><td><span class="remove remove-row"><i class="glyphicon glyphicon-trash"></i></span></td><td><input type="text" name="codes[]" placeholder="CODES" class="form-control"/></td><td><input type="text" name="production[]" placeholder="production" class="form-control"/></td><td><input type="text" name="reg_no[]" placeholder="reg_no" class="form-control"/></td><td><input type="number" name="quantity1[]" class="form-control"/></td><td id="total1"><input type="number" placeholder="total" name="total[]" class="form-control"/></td></tr></tbody></table></div>';
if(x <= max){
$("#products").append(html);
x++;
}
});
$("#table_field").on('click','#remove',function(){
$(this).closest('tr').remove();
/*x--;*/
});
});
</script>
</head>
<body>
<div class="container">
<center>
<h1 style="padding-bottom: 50px;">CODE LIST</h1>
</center>
<form>
<div class="form-group">
<label class="control-label col-sm-2">Consignee</label>
<div class="col-sm-10">
<input type="text" name= "consignee" class="form-control" placeholder="Enter Consignee">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Exported TO</label>
<div class="col-sm-10">
<input type="text" name="exportedto" class="form-control" placeholder="Enter Exported TO">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">PO</label>
<div class="col-sm-10">
<input type="text" name="po" class="form-control" placeholder="PO">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Brand</label>
<div class="col-sm-10">
<input type="text" name="brand" class="form-control" placeholder="Enter Brand">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">INV NO</label>
<div class="col-sm-10">
<input type="text" name="invno" class="form-control" id="invno" placeholder="Enter INV NO">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product">PRODUCT</label>
<div class="col-sm-10">
<input type="text" name="product" class="form-control" id="product" placeholder="Enter Product">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="packing">Type of Packing</label>
<div class="col-sm-10">
<input type="text" name="packing" class="form-control" id="packing" placeholder="Type of Packing">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<button id="add_product" type="button" class="btn btn-warning">Add Product</button>
</div>
</div>
<div id="products">
<div class="table-content">
<div style="padding-bottom: 20px;">
<button type="button" class="btn btn-primary add-row" style="margin-right: 10px;">Add Codes</button>
<button type="button" class="btn btn-info add-col">Add Grades</button>
</div>
<table class="table table-bordered table-hover table-sortable">
<thead>
<tr>
<tr><th></th><th colspan="3" class="text-center">CODES</th><th class="text-center">GRADES</th></tr>
<tr>
<th>Delete code</th>
<th class="text-center">
CODES
</th>
<th class="text-center">
PRODUCTION
</th>
<th class="text-center">
REGN NO
</th>
<th class="text-center">
<select name="grade1" id="grade1" class="form-control">
<option value="0">Select</option>
<option value="13/15">13/15</option>
<option value="16/20">16/20</option>
<option value="21/25">21/25</option>
<option value="26/30">26/30</option>
<option value="31/40">31/40</option>
<option value="41/50">41/50</option>
<option value="51/60">51/60</option>
<option value="61/70">61/70</option>
<option value="71/90">71/90</option>
<option value="91/110">91/110</option>
</select>
</th>
<th id="total">TOTAL</th>
</tr>
</tr>
</thead>
<tbody>
<tr>
<td><span class="remove remove-row"><i class="glyphicon glyphicon-trash"></i></span></td>
<td>
<input type="text" name='codes[]' placeholder='CODES' class="form-control"/>
</td>
<td>
<input type="text" name='production[]' placeholder='production' class="form-control"/>
</td>
<td>
<input type="text" name='reg_no[]' placeholder='reg_no' class="form-control"/>
</td>
<td>
<input type="number" name="quantity1[]" class="form-control"/>
</td>
<td id="total1">
<input type="number" placeholder="total" name="total[]" class="form-control"/>
</td>
</tr>
</tbody>
</table>
</div>
<div id="packing-list">
<h4 style="color: red">Packing List</h4>
<table class="table table-bordered table-hover table-sortable" id="packing-list">
<thead>
<tr>
<tr>
<th>S.No</th>
<th class="text-center">
DAY CODE
</th>
<th class="text-center">
SOURCE CODE
</th>
<th class="text-center">
HON QTY IN Kgs
</th>
<th class="text-center">
USED QTY IN Kgs
</th>
<th class="text-center">AFTER HEAD LESS IN Kgs</th>
<th class="text-center">
PEELING IN Kgs
</th>
<th class="text-center">
SOAK OUT IN Kgs
</th>
<th class="text-center">
FINISH PRODUCT IN Kgs
</th>
<th class="text-center">
FINISH PRODUCT IN M/c
</th>
</tr>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" name='codes[]' placeholder='CODES' class="form-control"/>
</td>
<td>
<input type="text" name='production[]' placeholder='production' class="form-control"/>
</td>
<td>
<input type="text" name='reg_no[]' placeholder='reg_no' class="form-control"/>
</td>
<td>
<input type="number" name="quantity1[]" class="form-control"/>
</td>
<td>
<input type="number" placeholder="total" name="total[]" class="form-control"/>
</td>
<td>
<input type="number" placeholder="total" name="total[]" class="form-control"/>
</td>
<td>
<input type="number" placeholder="total" name="total[]" class="form-control"/>
</td>
<td>
<input type="number" placeholder="total" name="total[]" class="form-control"/>
</td>
<td>
<input type="number" placeholder="total" name="total[]" class="form-control"/>
</td>
</tr>
<tr>
<th colspan="4" class="text-center">TOTAL</th>
<th>Total 1</th>
<th>Total 2</th>
<th>Total 3</th>
<th>Total 4</th>
<th>Total 5</th>
<th>Total 6</th>
</tr>
<tr>
<th colspan="5" class="text-center">YEILD %</th>
<th>%</th>
<th>%</th>
<th>%</th>
<th>%</th>
<th>%</th>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</div>
<!-- <center>
<input type="submit" class="btn btn-success" name="codelist" id="save" value="submit">
</center> -->
</body>
<script type="text/javascript">
// we're binding a lot of different click event-handlers to this element
// there's no point looking it up every time we do so:
var body = $('body');
// binding the click event for the add-row button:
body.on('click', 'button.add-row', function() {
// getting the relevant <table>:
var table = $(this).closest('div.table-content'),
// and the <tbody> and <thead> elements:
tbody = table.find('tbody'),
thead = table.find('thead');
// if the <tbody> has children:
if (tbody.children().length > 0) {
// we find the last <tr> child element, clone it, and append
// it to the <tbody>:
tbody.find('tr:last-child').clone().appendTo(tbody);
} else {
// otherwise, we create the basic/minimum <tr> element:
var trBasic = $('<tr />', {
'html': '<td><span class="remove remove-row"><i class="glyphicon glyphicon-trash"></span></td><td><input type="text" class="form-control" /></td>'
}),
// we find the number of columns that should exist, by
// looking at the last <tr> element of the <thead>,
// and finding out how many children (<th>) elements it has:
columns = thead.find('tr:last-child').children().length;
// a for loop to iterate over the difference between the number
// of children in the created trBasic element and the current
// number of child elements of the last <tr> of the <thead>:
for (var i = 0, stopWhen = columns - trBasic.children.length; i < stopWhen; i++) {
// creating a <td> element:
$('<td />', {
// setting its text:
'text': 'static element'
// appending that created <td> to the trBasic:
}).appendTo(trBasic);
}
// appending the trBasic to the <tbody>:
tbody.append(trBasic);
}
var table = $(this).closest('div.packing-list'),
// and the <tbody> and <thead> elements:
tbody = table.find('tbody'),
thead = table.find('thead');
// if the <tbody> has children:
if (tbody.children().length > 0) {
// we find the last <tr> child element, clone it, and append
// it to the <tbody>:
tbody.find('tr:last-child').clone().appendTo(tbody);
} else {
// otherwise, we create the basic/minimum <tr> element:
var trBasic = $('<tr />', {
'html': '<td><span class="remove remove-row"><i class="glyphicon glyphicon-trash"></span></td><td><input type="text" class="form-control" /></td>'
}),
// we find the number of columns that should exist, by
// looking at the last <tr> element of the <thead>,
// and finding out how many children (<th>) elements it has:
columns = thead.find('tr:last-child').children().length;
// a for loop to iterate over the difference between the number
// of children in the created trBasic element and the current
// number of child elements of the last <tr> of the <thead>:
for (var i = 0, stopWhen = columns - trBasic.children.length; i < stopWhen; i++) {
// creating a <td> element:
$('<td />', {
// setting its text:
'text': 'static element'
// appending that created <td> to the trBasic:
}).appendTo(trBasic);
}
// appending the trBasic to the <tbody>:
tbody.append(trBasic);
}
});
body.on('click', 'span.remove-row', function() {
$(this).closest('tr').remove();
});
body.on('click', 'span.remove-col', function() {
// getting the closest <th> ancestor:
var cell = $(this).closest('th'),
// getting its index with jQuery's index(), though
// cell.prop('cellIndex') would also work just as well,
// and adding 1 (JavaScript is zero-based, CSS is one-based):
index = cell.index() + 1;
// finding the closest <table> ancester of the <th> containing the
// clicked <span>:
cell.closest('table')
// finding all <td> and <th> elements:
.find('th, td')
// filtering that collection, keeping only those that match
// the same CSS-based, using :nth-child(), index as the <th>
// containing the clicked <span>:
.filter(':nth-child(' + index + ')')
// removing those cells:
.remove();
});
body.on('click', 'button.add-col', function() {
// finding the table (because we're using it to find both
// the <thead> and <tbody>:
var table = $(this).closest('div.table-content').find('table'),
thead = table.find('thead'),
// finding the last <tr> of the <thead>:
lastTheadRow = thead.find('tr:last-child'),
tbody = table.find('tbody');
att = table.find('#total');
// creating a new <th>, setting its innerHTML to the string:
$('<th>', {
'html': '<select name="grade1" id="grade1" class="form-control pull-left"><option value="0">Select</option><option value="13/15">13/15</option><option value="16/20">16/20</option><option value="21/25">21/25</option><option value="26/30">26/30</option><option value="31/40">31/40</option><option value="41/50">41/50</option><option value="51/60">51/60</option><option value="61/70">61/70</option><option value="71/90">71/90</option><option value="91/110">91/110</option></select><span class="pull-left remove remove-col"><i class="glyphicon glyphicon-trash"></span>'
// appending that created <th> to the last <tr> of the <thead>:
}).insertBefore(att);
// creating a <td>:
$('<td>', {
// setting its text:
'html': '<input type="number" name="quantity1[]" class="form-control"/>'
// inserting the created <td> after every <td> element
// that is a :last-child of its parent:
}).insertBefore('td:last-child');
});
</script>
</html>

Reset calculation after adding row to table

I'm trying to add row to table dynamically and calculates the age from ID card number.
ID card number for example: 88xxxxxxxxxx (age 33) // 00xxxxxxxxxx (age 21) // 01xxxxxxxxxx (age 20) and so on.
Problem here, as I'm adding row to the table. First row works fine but for the following rows, the results of age selector is applied to all rows in the table.
I've tried to clear the input of age class as new rows are added but seems like it removes all the input of the age selector as well.
var num = 0;
//adds row to table
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="${++num}">
<td class="row-index text-center">
<p>${num}</p>
</td>
<td class="row-index text-center">
<input type="text" class="form-control name">
</td>
<td class="row-index text-center">
<input type="text" class="form-control noic">
</td>
<td class="row-index text-center">
<input type="text" class="form-control age">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button"><span class="glyphicon glyphicon-minus"></span></button>
</td>
</tr>`);
$(".noic").blur(function() {
var currentYear = new Date().getFullYear().toString().substr(-2); // 20(21)
var yearNow = new Date().getFullYear(); // 2021
var yearID = $(".noic").val().substring(0, 2); // from ID: (88)xxxxxxxxxx
var age;
if (yearID > currentYear) {
age = (+yearNow - (+1900 + +yearID));
} else {
age = (+yearNow - (+2000 + +yearID));
}
$(".age").val(age);
});
});
// removes row from table
$('#tbody').on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
num--;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">No.</th>
<th class="text-center">Name</th>
<th class="text-center">ID Card Number</th>
<th class="text-center">Age</th>
<th class="text-center"><button class="btn btn-md btn-primary" id="addBtn" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
You need to use $(this) to get a reference to the currently blurred .noic, and use it as a reference to access itself and it's sibling elements:
var num = 0;
//adds row to table
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="${++num}">
<td class="row-index text-center">
<p>${num}</p>
</td>
<td class="row-index text-center">
<input type="text" class="form-control name">
</td>
<td class="row-index text-center">
<input type="text" class="form-control noic">
</td>
<td class="row-index text-center">
<input type="text" class="form-control age">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button"><span class="glyphicon glyphicon-minus"></span></button>
</td>
</tr>`);
$(".noic").blur(function() {
var currentYear = new Date().getFullYear().toString().substr(-2); // 20(21)
var yearNow = new Date().getFullYear(); // 2021
var yearID = $(this).val().substring(0, 2); // from ID: (88)xxxxxxxxxx
var age;
if (yearID > currentYear) {
age = (+yearNow - (+1900 + +yearID));
} else {
age = (+yearNow - (+2000 + +yearID));
}
$(this).closest("tr").find(".age").val(age);
});
});
// removes row from table
$('#tbody').on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
num--;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">No.</th>
<th class="text-center">Name</th>
<th class="text-center">ID Card Number</th>
<th class="text-center">Age</th>
<th class="text-center"><button class="btn btn-md btn-primary" id="addBtn" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>

How to save data from html table to database in Laravel

I enter data from text field to html table rows by using JavaScript. Then I need to save them in a mysql table one by one. so I want to know how to save them to database.
I put the coding below.
function addRow() {
var table = document.getElementById("tbody");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var items = document.getElementById("item").value;
var suppliers = document.getElementById("supplier").value;
var quantities = document.getElementById("quantity").value;
var grnprices = document.getElementById("grnprice").value;
if (items == "", suppliers == "", quantities == "", grnprices == "") {
alert("Please fill the Required Field");
} else {
var values = parseInt(document.getElementById('rawno').value, 10);
values = isNaN(values) ? 0 : values;
values++;
document.getElementById('rawno').value = values;
var total = quantities * grnprices;
row.insertCell(0).innerHTML = values;
row.insertCell(1).innerHTML = items;
row.insertCell(2).innerHTML = suppliers;
row.insertCell(3).innerHTML = quantities;
row.insertCell(4).innerHTML = "Rs. " + grnprices;
row.insertCell(5).innerHTML = "Rs. " + total;
row.insertCell(6).innerHTML = '<button type ="button" class="btn btn-danger" onClick="Javacsript:deleteRow(this)"> <i class="fa fa-trash-o"></i></button>';
}
}
<table class="table table-striped">
<thead>
<tr>
<th scope="col" width="200">Item</th>
<th scope="col" width="200">Supplier</th>
<th scope="col" width="200">Quantity</th>
<th scope="col" width="200">GRN Price</th>
<th scope="col" width="50"></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" min="0" class="form-control" name="item" id="item">
</td>
<td>
<input type="number" min="0" class="form-control" name="supplier" id="supplier">
</td>
<td>
<input type="number" min="1" class="form-control" name="quantity" id="quantity">
</td>
<td>
<input type="number" min="0" class="form-control" name="grnprice" id="grnprice">
</td>
<td>
<input type="button" class="btn btn-info" id="add" value="Add" onclick="Javascript:addRow()">
</td>
<td>
<input type="hidden" name="rawno" id="rawno">
</td>
</tr>
</tbody>
</table>
</div>
<table class="table" id="myTableData">
<thead>
<tr>
<th>No</th>
<th>Item</th>
<th>Supplier</th>
<th>Quantity</th>
<th>GRN Price</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody id="tbody">
<tr></tr>
</tbody>
</table>
<button type="button" class="btn btn-success" onclick="grnConfirmation()">Save</button>
Can anyone show an example.
First of all, you need to group all the input data which you want to save in database to a form which pointed to the controller method. Then the controller will do all the job.
Assuming you write the front-end in blade file : create.blade.php
<form method="POST" action="ItemInfoController#store">
<input type="text" min="0" class="form-control" name="item" id="item">
<input type="number" min="0" class="form-control" name="supplier" id="supplier">
<input type="number" min="1" class="form-control" name="quantity" id="quantity">
<input type="number" min="0" class="form-control" name="grnprice" id="grnprice">
<input type="submit" value="submit">
</form>
In ItemInfoController.php :
public function store(Request $request) {
// This will add the data from input to the database.
// You can change the query builder as you need.
DB::table('item')->insert(['item' => $request->item,
'supplier' => $request->supplier,
'quantity' => $request->quantity]);
}
If you want to use Eloquent you can just change the DB query with the model you use.
Example : ItemInfo::create($request);

How to automatically calculate the total price of each table row after appending the row using javascript?

Please am creating a POS application in laravel and want to automatically calculate the Price total for each row anytime I append a table row. I need assistance. Thank you
My Code below
<table class="table table-head-fixed text-nowrap" id="myTable">
<thead>
<tr>
<th>Qty</th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Tax</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="main_data">
<td><input type="number" name="items[0][inv_quantity]" class="form-control quantity" onkeyup="cal()" id="qty_invoice" style="width: 70px"></td>
<td>
<select name="items[0][inv_item]" class="form-control item" style="width: 250px">
<option>Items</option>
</select>
</td>
<td><input type="text" name="items[0][inv_desc]" class="form-control description" style="width: 400px"></td>
<td><span class="tag tag-success"><input type="text" name="items[0][inv_price]" class="form-control u_price" onkeyup="cal()" id="price_invoice" style="width: 150px"></span></td>
<td><span class="tag tag-success"><input type="text" name="items[0][inv_tax]" class="form-control tax" style="width: 150px"></td>
<td><span class="tag tag-success"><input type="text" name="items[0][inv_total]" id="total" class="form-control amount" style="width: 150px"></td>
<td>
<span><button class="btn btn-default" type="button" onclick="remove()"><i class="fa fa-trash" aria-hidden="true"></i></button></span>
<span><button type="button" onclick="myFunction()" class="btn btn-default"><i class="fa fa-plus" aria-hidden="true"></i> Add Row</button></span>
</td>
</tr>
</tbody>
</table>
script
<script type="text/javascript">
var int = 1;
function myFunction() {
var tr = '<tr>'+
'<td class="table_field main_data"><input type="number" name="items['+ (int) +'][inv_quantity]" class="form-control quantity" style="width: 70px"></td>'+ '<td><select name="items['+ (int) +'][inv_item]" class="form-control item" style="width: 250px"><option>Items</option></select></td>'+'<td><input type="text" name="items['+ (int) +'][inv_desc]" class="form-control description" style="width: 400px"></td>'+'<td><span class="tag tag-success"><input type="text" name="items['+ (int) +'][inv_price]" class="form-control u_price" style="width: 150px"></span></td>'+'<td><span class="tag tag-success"><input type="text" name="items['+ (int) +'][inv_tax]" class="form-control tax" style="width: 150px"></td>'+'<td><span class="tag tag-success"><input type="text" name="items['+ (int) +'][inv_total]" class="form-control amount" style="width: 150px"></td>'+'<td><span><button class="btn btn-default" type="button" onclick="remove()"><i class="fa fa-trash" aria-hidden="true"></i></button></span><span><button type="button" onclick="myFunction()" class="btn btn-default"><i class="fa fa-plus" aria-hidden="true"></i> Add Row</button></span</td>'
'</tr>';
$('tbody').append(tr);
int++;
}
function cal(){
var qty= document.getElementById('qty_invoice').value;
var unit = document.getElementById('price_invoice').value;
var total = parseInt(qty*unit);
document.getElementById('total').value = total;
console.log(total);
}
</script>
Am only able to auto calculate for the first row, It doesn't work on the rest after appending the row. Any assistance please
You can use watch property; have rows from you'r response saved in a variable like rows and put it in watch so every time a new row gets added you can calculate it.
E.g:
data() {
return {
rows:[]
}
},
watch: {
rows(val) {
console.log("new row", val)
this.cal
}
}

Issue Submitting Dynamic Form After Deleting Row

I have a form that I am building with a table, I want to be able to add or delete rows to this form and submit.
Here is a js.fiddle for my form
https://jsfiddle.net/oyvk1whx/
<form asp-controller="Institution" asp-action="AccountCategoryFees" method="post" class="form-horizontal">
<div asp-validation-summary="All" class="text-danger"></div>
<input asp-for="AccountCategoryId" type="hidden"/>
<table class="table table-responsive" id="feeTable">
<thead>
<tr>
<td><strong>Description</strong></td>
<td><strong>Price</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
#for (int j = 0; j < Model.Fees.Count; j++)
{
<tr>
<td>
<input asp-for="Fees[j].Description" />
</td>
<td>
<span style="position: absolute; margin-left: 2px; margin-top: 8px;">$</span><input asp-for="Fees[j].Price" type="number" min="0.00" step="0.0001" max="2500" class="form-control" />
</td>
<td>
<input type="button" class="deleteButton btn btn-md btn-danger" value="Delete">
</td>
</tr>
}
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" style="color:gray" value="Add Fee" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<div class="modal-footer" style="padding:0px;">
<button type="submit" class="btn bg-primary">Save</button>
</div>
</form>
<script>
var feeTypes = #Html.Raw(Json.Serialize(#Model.Fees));
</script>
<script>
var counter = #Model.Fees.Count;
$('#feeTable').on("click", "#addrow", function () {
var cols = "<tr>";
cols += '<td><input id="Fees_' + counter + '__Description" name="Fees[' + counter + '].Description"/></td>';
cols += '<td><span style="position: absolute; margin-left: 2px; margin-top: 8px;">$</span><input id="Fees_' + counter + '__Price" name="Fees[' + counter + '].Price" type="number" min="0.00" step="0.0001" max="2500" value="0" class="form-control"/></td>';
cols += '<td><input type="button" class="deleteButton btn btn-md btn-danger" value="Delete"></td>';
cols += '</tr>';
$("#feeTable").append(cols);
counter++;
});
$(document).on("click", ".deleteButton", function (event) {
$(this).closest("tr").remove();
});
</script>
The script works fine for adding new rows and deleting rows. The issue is when I delete a row the form no longer submits correctly, all rows after the deleted one are ignored.
I believe this is because of the disconnect in the ids, since there is a gap the model binder cannot parse it.
Any suggestions?
I believe this is because of the disconnect in the ids, since there is a gap the model binder cannot parse it
I would suggest to avoid square brackets in names and/or ids if possible and to solve your issue on your server side. In any case, if you need to rearrange IDs and NAMEs attributes you can simply cycle on each table row (because on server side you will handle only names, you can rearrange only these) :
$('#feeTable tr:has(input.deleteButton)').each(function(rIdx, row) {
$(row).find('[id^=Fees_]').each(function(cIdx, col) {
// col.id = col.id.replace(/\d+/, rIdx);
col.name = col.name.replace(/\d+/, rIdx);
});
})
var counter = 0;
$('#feeTable').on("click", "#addrow", function () {
var cols = "<tr>";
cols += '<td><input id="Fees_' + counter + '__Description" name="Fees[' + counter + '].Description"/></td>';
cols += '<td><span style="position: absolute; margin-left: 2px; margin-top: 8px;">$</span><input id="Fees_' + counter + '__Price" name="Fees[' + counter + '].Price" type="number" min="0.00" step="0.0001" max="2500" value="0" class="form-control"/></td>';
cols += '<td><input type="button" class="deleteButton btn btn-md btn-danger" value="Delete"></td>';
cols += '</tr>';
$("#feeTable").append(cols);
counter++;
});
$(document).on("click", ".deleteButton", function (event) {
$(this).closest("tr").remove();
$('#feeTable tr:has(input.deleteButton)').each(function(rIdx, row) {
$(row).find('[id^=Fees_]').each(function(cIdx, col) {
// col.id = col.id.replace(/\d+/, rIdx);
col.name = col.name.replace(/\d+/, rIdx);
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-responsive" id="feeTable">
<thead>
<tr>
<td><strong>Description</strong></td>
<td><strong>Price</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" style="color:gray" value="Add Fee" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<button type="submit" class="btn bg-primary">Save</button>

Categories