Dynamic row calculation with Jquery - javascript

I want to make sum of dynamic rows and addition.
<div class="row">
<div class="col-md-8">
<div class="table-responsive">
<table id="test-table" class="table table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price </th>
<th><input id='add-row' class='btn btn-primary' type='button' value='Add' /> </th>
</tr>
</thead>
<tbody id="test-body">
<tr id="row0" class="products">
<td>
<select name="product_id[]" id="" class="form-control">
<option value="">-- Select Product --</option>
#foreach ($product as $row )
<option value="{{ $row->id }}">{{ $row->product_name }}</option>
#endforeach
</select>
</td>
<td>
<input name="price[]" type="number" min="1" class="form-control input-md price" />
</td>
<td>
<input class="delete-row btn btn-primary" type="button" value="Delete" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<div class="col-xs-6">
<p>Previous Due</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control" value="5000" readonly>
</div>
<div class="col-xs-6">
<p>Total Price</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control total_price" value="" readonly>
</div>
<div class="col-xs-6">
<p>Pay Now</p>
</div>
<div class="col-xs-6">
<input type="number" class="form-control">
</div>
<div class="col-xs-6">
<p>Total Due</p>
</div>
<div class="col-xs-6">
<input type="number" value="" class="form-control">
</div>
</div>
</div>
Script:
<script type="text/javascript">
var row=1;
$(document).on("click", "#add-row", function () {
var new_row = '<tr id="row' + row + '" class="products"><td> <select name="product_id[]' + row + '" id="" class="form-control"> <option value="">-- Select Product --</option> #foreach ($product as $row ) <option value="{{ $row->id }}">{{ $row->product_name }}</option>#endforeach </select></td><td><input name="price[]' + row + '" type="number" min="1" class="form-control price" /></td><td><input class="delete-row btn btn-primary" type="button" value="Delete" /></td></tr>';
$('#test-body').append(new_row);
row++;
return false;
});
$(document).on("click", ".delete-row", function () {
if(row>0) {
$(this).closest('tr').remove();
row--;
}
return false;
});
</script>
<script type="text/javascript">
function sumIt() {
var total = 0, val;
$('.price').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('.total_price').val(Math.round(total));
}
$(function() {
$(document).on('input', '.price', sumIt);
sumIt()
});
</script>
If I delete product row, the total price field is not updating the calculation. Suppose I added 4 rows, and give price value, after that I remove two rows, but the total price holds the previous 4 rows sum, it didn't update when I remove any row.
Here I want to show the total sum of product in total price.
And the Total Due calculation will be total due = (previous due + total price)- pay now
thanks

Related

Javascript/Jquery : How can I show value which match with selected value on dynamic table?

I have a dynamic table where button on click add new row. Each row has a select value for product name and a input value for product price. I want to show the product price depends on the selected value. For backed I used Laravel 7. Below I added my code:
Table:
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control" id="product-name">
<option value="" selected disabled>Select Product</option>
#foreach($product as $row)
<option value="{{ $row->id }}">{{ $row->name }}</option>
#endforeach
</select>
</td>
<td>
#foreach($product as $row)
<input id="price_{{ $row->id }}" value="{{ $row->price }}" type="number" class="form-control price" style="display:none;">
#endforeach
</td>
<td><button class="remove">Delete</button></td>
</tr>
</tbody>
</table>
This is the script where button on click add a new row:
$(function() {
const $tb = $('#product-table tbody');
$(".delete").eq(0).hide()
$("#productAdd").on("click",function() {
const $row = $tb.find("tr").eq(0).clone();
$(".delete",$row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
Here I show all the product price and all are hidden. I want to show the price value which match with the selected value. For this I used id = price_{{ $row->id }}
#foreach($product as $row)
<input id="price_{{ $row->id }}" value="{{ $row->price }}" type="number" class="form-control price" style="display:none;">
#endforeach
And this is my script where showed the product price:
$('#product-name').on('change',function(){
$(".price").hide();
var price = $(this).find('option:selected').val();
$("#price_" + price).show();});
But this works for the first row only. How can I merge this script, so that it works for every new row added inside the table?
$(function() {
const $tb = $('#product-table tbody');
$(".remove").eq(0).hide()
$("#productAdd").on("click",function() {
const $row = $tb.find("tr").eq(0).clone();
$(".remove",$row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
$('#product-name').on('change',function(){
$(".price").hide();
var price = $(this).find('option:selected').val();
$("#price_" + price).show();});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control" id="product-name">
<option value="" selected disabled>Select Product</option>
<option value="1">Pant</option>
<option value="2">Shirt</option>
<option value="3">T-shirt</option>
</select>
</td>
<td>
<input id="price_1" value="100" type="number" class="form-control price" style="display:none;">
<input id="price_2" value="200" type="number" class="form-control price" style="display:none;">
<input id="price_3" value="50" type="number" class="form-control price" style="display:none;">
</td>
<td><button class="remove">Delete</button></td>
</tr>
</table>
With proper delegation it will work
As I said in my other answer, do not use ID
Here is a working version. See I changed the ID to class
$(function() {
const $tb = $('#product-table tbody');
$(".remove").eq(0).hide()
$("#productAdd").on("click", function() {
const $row = $tb.find("tr").eq(0).clone();
$(".remove", $row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$tb.on('change', '.product-name', function() {
const $row = $(this).closest('tr');
$(".price", $row).hide();
const whichPrice = $(this).val();
if (whichPrice != "") $(".price", $row).eq(whichPrice-1).show()
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control product-name">
<option value="" selected disabled>Select Product</option>
<option value="1">Pant</option>
<option value="2">Shirt</option>
<option value="3">T-shirt</option>
</select>
</td>
<td>
<input value="100" type="number" class="form-control price" style="display:none;">
<input value="200" type="number" class="form-control price" style="display:none;">
<input value="50" type="number" class="form-control price" style="display:none;">
</td>
<td><button class="remove">Delete</button></td>
</tr>
</table>

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

How to make a dynamic change and access a parent element on a value using JQuery?

I have a form where it is related to my previous question here. What I want to do is to get the previous value inside my input element labeled "SERIAL END" then automatically appends it's value when adding a row to "SERIAL START", and not only append but will add +1 to it's value (this is solved), but I want to add a function when the value is already added, it will get the value of the edited parent element and can be changeable but still adds the children element's value by +1.
Here is my whole code
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var lasttr = $('#tbl tr:last').attr('id');
var lastinsertedrow = lasttr.replace('tablerow_', '');
var end = $('#serend' + lastinsertedrow).val();
end = (parseInt(end) + parseInt(1));
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" required><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
echo "<option value=$row[id]>".$row['model_name'].
" </option>";
}
} ? > < /select></td > ';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="text" class="form-control" id="serstart' + hidden +
'" name="serstart[]" value="' + end + '" readonly/></td>';
cols +=
'<td><input type="text" class="form-control" id="serend' + hidden +
'" name="serend[]" onchange="myChangeFunction(this)" required /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
$("#serend" + hidden).on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
}
})
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
include ('../include/header_pis.php');
?>
<html>
<title>Lot_Registration</title>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header"> Lot Registration
<a href="rbg_table.php">
<button class="btn btn-success pull-right">
<span class="fa fa-reply"> Back </span>
</button>
</a>
</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Model Form
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form class="className" name="form" id="form" action="lot_registration_model_submit.php" data-toggle="validator" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno" name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof" name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serstart" name="serstart" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serend" name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model
left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
} ?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="text" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="text" name="serend[]" id="serend0" class="form-control" onchange="myChangeFunction(this)" required />
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
As i said in comment you just need to get index of tr where input has changed and then using that access next tr input and add value there.
Demo Code :
$("[id*=serend]").on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
} else {
//get index of tr
var row = $(this).closest('tr').index() + 1;
var end = $(this).val(); //get value of input change
end = (parseInt(end) + parseInt(1));
$("tbody tr:eq(" + row + ") td:eq(2) input").val(end) //add inside next input
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
<tr id="tablerow_1">
<td>
<select name="model[]" id="model1" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code1" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart1" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend1" value="" class="form-control"> </td>
</tr>
<tr id="tablerow_2">
<td>
<select name="model[]" id="model2" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code2" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart2" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend2" value="" class="form-control"> </td>
</tr>
</tbody>
</table>

How to concatenate two array format to Json using javascript

I have 5 input fields and one dynamic table, i created a json format when user enterd data, my problem is its comes 2 arrays, one array is that 5 input fields data and another one array is dynamic table data. but i want single array It means example json format given below.
how can i merge that two jsons?
Please refer my fiddle and check console..
FIDDLE HERE
I want json look like,
I want json like
$('form').submit(function(e) {
e.preventDefault();
var data = {
"voucNum": $('#vocNum').val(),
"vochDate": $('#vochDate').val(),
"refno": $('#cashref').val(),
"billtype": $('#cashbill').val(),
"acctname": $('#cashAc').val(),
"tds": $('#cashTds').val(),
"total": $('#totaldbt').val(),
"amount": $('#cashAmt').val(),
"availableamt": $('#cash_bal').val(),
"acctname": $('#payacc').val(),
"cashpayment": [{
"narr": $('#pay_narrat').val(),
"acctcode": $('#payacc_code').val(),
"debit": $('#paydeb').val(),
"actname": $('#payacc').val(),
"credit": $('#paycredit').val()
},
{
"narr": $('#acc_narrat').val(),
"acctcode": $('#cashAcctcode').val(),
"debit": $('#cashdeb').val(),
"accountName": $('#accountName').val(),
"credit": $('#crditCash').val()
}
]
}
console.log(data);
});
Here is my Actual code
// Table dynamic with Json format
var status;
var sno = [];
var load;
var no_rows = 0;
var row;
function submitVal() {
var mainArr = [];
var tmpArr = [];
var mainTable = $('#tab_logic');
var tr = mainTable.find('tbody tr');
console.log(tr.length)
tr.each(function() {
tmpArr = [];
$(this).find('td').each(function() {
//get attr id
let title = $(this).find('input, selet').attr('id');
var values = $(this).find('input, select').val();
//input json format
let pushing = $.parseJSON('{ "' + title + '": "' + values + '" }');
tmpArr.push(pushing);
});
mainArr.push(tmpArr);
});
console.log(mainArr);
}
$(document).ready(function() {
$(".add_Row").click(function() {
row = `<tr id="tasklist" class="jsrow"><td><input type="text" class="sno sel_text form-control" placeholder="A/c code" id=""cashAcctcode name="acctcode"></input></td><td><select class="sel_sel form-control status" for="accountName" id="accountName" name="accountName"><option value="">Choose an items</option><option value="acc1">Account 1</option><option value="acc2">Account 2</option><option value="acc3">Account 3</option></select></td><td><input type="text" class="form-control pname" placeholder='Enter your text here' name="narr" id='acc_narrat' data-toggle='modal' data-target='#accnarratModal'></input></td><td><input type="text" placeholder='Debit Amount' class='form-control task input-md' for="debit" name="debit" id='cashdeb' data-action='sumDebit'></input></td><td><input type="text" placeholder='Credit Amount' data-action='sumCredit' class='form-control comment input-md' name="credit" for="credit" id="crditCash" readonly></input></td><td><a class="dlt-icon"><button type="button" class="adRow" style="width:70%;">x</button></a></td></tr>`;
$("table > tbody").append(row);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
bindScript();
});
$('form').submit(function() {
submitVal();
});
});
(function($) {
$.fn.serializeFormJSON = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$('form').submit(function(e) {
e.preventDefault();
var data = {
"voucNum": $('#vocNum').val(),
"vochDate": $('#vochDate').val(),
"refno": $('#cashref').val(),
"billtype": $('#cashbill').val(),
"acctname": $('#cashAc').val(),
"tds": $('#cashTds').val(),
"total": $('#totaldbt').val(),
"amount": $('#cashAmt').val(),
"availableamt": $('#cash_bal').val(),
"acctname": $('#payacc').val(),
"cashpayment": [{
"narr": $('#pay_narrat').val(),
"acctcode": $('#payacc_code').val(),
"debit": $('#paydeb').val(),
"actname": $('#payacc').val(),
"credit": $('#paycredit').val()
},
{
"narr": $('#acc_narrat').val(),
"acctcode": $('#cashAcctcode').val(),
"debit": $('#cashdeb').val(),
"accountName": $('#accountName').val(),
"credit": $('#crditCash').val()
}
]
};
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal" action="" method="post" id="contactForm">
<div class="row">
<!-- voucher number -->
<div class="col-4">
<label class="col-sm-8 control-label p-sm-0" for="vouchno">Voucher Number :</label>
<input type="number" id="vocNum" value="1" class="form-control vocnum-box" name="vouchno" readonly />
</div>
<!-- voucher date -->
<div class="form-group col-3 rfdate">
<label class="col-sm-5 control-label p-sm-0" for="vouchdt">Voucher Date :</label>
<div class="input-group vcdate datepic" id="vocdate">
<input type="text" class="form-control" id="vochDate" name="vouchdt" />
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar"></i>
</span>
</div>
</div>
</div>
<!-- Reference number -->
<div class="row">
<div class="col-4">
<label class="col-sm-12 control-label p-sm-0" for="RefNumber">Ref Number :</label>
<input type="number" id="cashref" placeholder="Optional" class="form-control" name="refno" />
</div>
<!-- Bill type -->
<div class="form-group col-4" style="margin-bottom: 0px;">
<label class="col-sm-12 control-label p-sm-0" for="billType">Bill type :</label>
<select class="form-control selectsch_items" name="billtype" id="cashbill" required>
<option value="null">Choose an items</option>
<option value="Raw">Raw Materials</option>
<option value="Spare">Spare</option>
<option id="othr_bill" value="Other">Others</option>
</select>
</div>
<!-- refer date -->
<div class="form-group col-3">
<label class="col-sm-6 control-label p-sm-0" for="refDate">Ref Date :</label>
<div class="input-group date datepic" id="referdate">
<input type="text" data-date-format="dd/mm/yy" class="form-control" name="referdate" id="refdate" />
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar"></i>
</span>
</div>
</div>
</div>
<div class="row">
<!-- cash account dropdown -->
<div class="form-group col-4" style="margin-bottom: 20px;">
<label class="col-sm-12 control-label p-sm-0 input-group" for="acctcode">Cash Account :</label>
<select class="form-control selectsch_items status" name="acctname" id="cashAc" required>
<option value="">Choose an items</option>
<option value="acc1">Account 1</option>
<option value="acc2">Account 2</option>
<option value="acc3">Account 3</option>
</select>
</div>
<!-- TDS Field -->
<div class="form-group col-4" style="margin-bottom: 20px;" id="tds_tx">
<label class="col-sm-12 control-label p-sm-0" for="tds">TDS :</label>
<select class="form-control selectsch_items" name="tds" id="cashTds" required>
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
</div>
<!-- Amount field -->
<div class="form-group col-3 amt_wid" id="amt_cash">
<label class="col-sm-12 control-label p-sm-0" for="amount">Amount :</label>
<input type="number" id="cashAmt" placeholder="Enter Amount Here" class="form-control" name="amount" required />
</div>
</div>
</form>
<!-- Cash payment Table -->
<form>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr style="background-color: #680779; color: #fff;">
<th class="text-center">
Account Code
</th>
<th class="text-center">
A/c Name*
</th>
<th class="text-center">
Narration*
</th>
<th class="text-center">
Debit*
</th>
<th class="text-center">
Credit
</th>
<th class="text-center">
Action
</th>
</tr>
</thead>
<tbody id="mainBody">
<tr id="fst_row">
<td>
<input type="number" id="payacc_code" placeholder='Enter A/c code' for="acctcode" name="acctcode" class="form-control sel_text" />
</td>
<td>
<select class="form-control sel_sel" id="payacc" name="actname" for="actname">
<option value="">Select TDS A/c name</option>
<option value="1">TDS A/c 1</option>
<option value="2">TDS A/c 2</option>
<option value="3">TDS A/c 3</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="pay_narrat" name="narr" for="narr" placeholder="Enter your text here" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="paydeb" value="100" name="debit" for="debit" placeholder='Debit Amount' data-action="sumDebit" class="form-control" readonly />
</td>
<td>
<input type="number" id="paycredit" name="credit" for="credit" placeholder='Credit Amount' data-action="sumCredit" class="form-control" readonly />
</td>
</tr>
<input type="button" class="add_Row adRow button-add" id="add_row" value="Add Row">
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- total debit and credit field -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
<input type="number" class="totalcredit" id="creditTotal" name="totalcredit" placeholder=" Total Credit Amount" value="200" style="margin-left: 8px;" readonly>
</div>
</div>
<!-- available amount field -->
<div class="form-group col-12">
<div class="input-group col-sm-12 p-sm-0">
<label class="col-sm-8 control-label p-sm-0">Available Amount :</label>
<div class="cash-avail">
<input type="text" value="dr" placeholder="Dr" class="form-control stc_accode" name="cash_dr" id="cash_dr" readonly />
<input type="text" placeholder="Available Amount" class="form-control stc_subcode" name="availableamt" id="cash_bal" for="availableamt" readonly />
</div>
</div>
</div>
<!-- Submit Button -->
<div class="form-group ml-auto mt-2 mb-0">
<div class="col-md-12 stockform_submit" id="">
<button type="submit" class="btn add-btn submit-btn load" id="cashSub">Submit</button>
<button type="reset" class="btn btn-default reset-btn stock_rst" style="left: 0%" id="reset-btn">Reset</button>
</div>
</div>
</form>
It took me a while to understand what you meant.
So you needed to merge two arrays: mainArr and tempArr, and instead of using concat you used push function that leads to the resulting array be an array with multiple arrays.
Just Replace,
mainArr.push(tmpArr);
to
mainArr = mainArr.concat(tmpArr);
I know, its a delayed answer and may be you had already fixed the issue. But
if it helps :)

Add two values of different textField to fill another textField on multiple lines

Whenever I input the value of quantity and unit cost for each line, I want to automatically display the multiplied result into the total cost field.
I wrote the jquery script below trying to figure out how to go about it but couldn't get it working
$('.unit, .quantity').on('change', function() {
// var quantity = $('#expenseslist-quantity').val();
// var unit = $('#expenseslist-unit_cost').val();
var total = 0;
$('.quantity, .unit').each(function(){
total = quantity * unit ;
});
$('#expenseslist-total_cost').val(total);
});
Kindly help.
Try to learn how to implement dynamic element
$('.unit, .quantity').on('change', function(event) {
var total1 = 0;
var total2 = 0;
var quantity1 = $('#expenseslist-quantity1').val();
var unit1 = $('#expenseslist-unit_cost1').val();
total1 = quantity1 * unit1 ;
$('#expenseslist-total_cost1').val(total1);
var quantity2 = $('#expenseslist-quantity2').val();
var unit2 = $('#expenseslist-unit_cost2').val();
total2 = quantity2 * unit2 ;
$('#expenseslist-total_cost2').val(total2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody>
<tr class="primary">
<td width="170">
<div class="form-group field-expenseslist-item_id">
<select id="expenseslist-item_id" class="form-control" name="ExpensesList[item_id][]" required="">
<option value="">Select an Item</option>
<option value="1">Vehicle General Repairs And Maintenance</option>
<option value="2">Transportation Cost</option>
</select>
<div class="help-block"></div>
</div>
</td>
<td width="450"><div class="form-group field-expenseslist-request_explanation">
<textarea id="expenseslist-request_explanation" class="form-control" name="ExpensesList[request_explanation][]" rows="2" required=""></textarea>
<div class="help-block"></div>
</div>
</td>
<td width="80"><div class="form-group field-expenseslist-quantity">
<input type="number" id="expenseslist-quantity1" class="form-control quantity" name="ExpensesList[quantity][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="130"><div class="form-group field-expenseslist-unit_cost">
<input type="number" id="expenseslist-unit_cost1" class="form-control unit" name="ExpensesList[unit_cost][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="150"><div class="form-group field-expenseslist-total_cost">
<input type="text" id="expenseslist-total_cost1" class="form-control total" name="ExpensesList[total_cost][]" value="0" readonly="readonly" required="">
<div class="help-block"></div>
</div>
</td>
<!-- <td>
<button>Add</button>
</td> -->
</tr>
<tr class="primary">
<td width="170">
<div class="form-group field-expenseslist-item_id">
<select id="expenseslist-item_id" class="form-control" name="ExpensesList[item_id][]" required="">
<option value="">Select an Item</option>
<option value="1">Vehicle General Repairs And Maintenance</option>
<option value="2">Transportation Cost</option>
</select>
<div class="help-block"></div>
</div>
</td>
<td width="450"><div class="form-group field-expenseslist-request_explanation">
<textarea id="expenseslist-request_explanation" class="form-control" name="ExpensesList[request_explanation][]" rows="2" required=""></textarea>
<div class="help-block"></div>
</div>
</td>
<td width="80"><div class="form-group field-expenseslist-quantity">
<input type="number" id="expenseslist-quantity2" class="form-control quantity" name="ExpensesList[quantity][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="130"><div class="form-group field-expenseslist-unit_cost">
<input type="number" id="expenseslist-unit_cost2" class="form-control unit" name="ExpensesList[unit_cost][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="150"><div class="form-group field-expenseslist-total_cost">
<input type="text" id="expenseslist-total_cost2" class="form-control total" name="ExpensesList[total_cost][]" value="0" readonly="readonly" required="">
<div class="help-block"></div>
</div>
</td>
<!-- <td>
<button>Add</button>
</td> -->
<td><div class="btn btn-sm btn-danger rmv">Delete</div></td></tr></tbody>
UPDATED ANSWER:
As per your recent information, I made required changes to the code.
PS: For this, you have to make some changes on your HTML too and have to insert data- attributes on them.
For Unit input: data-type="unit" data-field="field_{1}"
For Quantity input: data-type="qty" data-field="field_{1}"
For the output input area: data-field-count="field_{1}"
After that, try out this code:
$('.unit, .quantity').on('keyup', function() {
let fieldType = $(this).data('type'),
fieldCount = $(this).data('field'),
intOne = $(this).val(),
intTwo = 1
if (fieldType == 'qty') {
intTwo = $('input[data-type=qty]').val()
} else {
intTwo = $('input[data-type=unit]').val()
}
let total = intOne * intTwo
$('input[data-field-count='+ fieldCount +']').val(total);
});
OLD ANSWER:
Since your query is pretty vague, this is what I understood from it:
$('.unit, .quantity').on('keyup', function() {
let qty = $('#expenseslist-quantity').val(),
unit = $('#expenseslist-unit_cost').val()
let total = unit * qty
$('#expenseslist-total_cost').val(total);
});
I don't know why you are using the each loop. Are there more than one unit and quantity fields?

Categories

Resources