How to concatenate two array format to Json using javascript - 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 :)

Related

Dynamic row calculation with Jquery

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

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>

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?

Use print button in modal

I am designing a receipt generator for client. The client add payment receipt using add button and after they click on submit they have option to convert it to pdf or print this. However since my form contains texxt field . It not printing it properly and only outputting the filled content.I tried using window.print but its dispalying boxes as well. Not sure how to proceed. below is the code:
I used the javascript but is unable to add classes
$('button[name="e_subPrint"]').click(function(){
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
var html = getPrintHtml("e_print");
mywindow.document.write(html);
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
});
function getPrintHtml(print){
var center = $('#'+print +' input[name="center"]').val();
var dated = $('#'+print +' input[name="dated"]').val();
var payment = $('#'+print +' input[name="payment"]').val();
var studname = $('#'+print +' input[name="studname"]').val();
var cnum = $('#'+print +' input[name="cnum"]').val();
var pnum = $('#'+print +' input[name="pnum"]').val();
var sum = $('#'+print +' input[name="sum"]').val();
var amt = $('#'+print +' input[name="amt"]').val();
var chnum = $('#'+print +' input[name="chnum"]').val();
var chdate = $('#'+print +' input[name="chdate"]').val();
var chbank = $('#'+print +' input[name="chbank"]').val();
var course = $('#'+print +' input[name="course"]').val();
var tfees = $('#'+print +' input[name="tfees"]').val();
var sgst = $('#'+print +' input[name="sgst"]').val();
var cgst = $('#'+print +' input[name="cgst"]').val();
var gtotal = $('#'+print +' input[name="gtotal"]').val();
var html = "<html><table>\n\
<tr><td>CENTER: </td><td>"+center+"</td></tr>\n\
<tr><td>DATED: </td><td>"+dated+"</td></tr>\n\
<tr><td>PAYMENT: </td><td>"+payment+"</td></tr>\n\
<tr><td>STUDENT NAME: </td><td>"+studname+"</td></tr>\n\
<tr><td>CONTACT NUMBER: </td><td>"+cnum+"</td></tr>\n\
<tr><td>PARENTAL CONTACT: </td><td>"+pnum+"</td></tr>\n\
<tr><td>TOTAL AMOUNT: </td><td>"+amt+"</td></tr>\n\
<tr><td>CHEQUE NUMBER: </td><td>"+chnum+"</td></tr>\n\
<tr><td>CHEQUE DATE: </td><td>"+chdate+"</td></tr>\n\
<tr><td>CHEQUE BANK: </td><td>"+chbank+"</td></tr>\n\
<tr><td>COURSE: </td><td>"+course+"</td></tr>\n\
<tr><td>TUITION FEES: </td><td>"+tfees+"</td></tr>\n\
<tr><td>SGST: </td><td>"+sgst+"</td></tr>\n\
<tr><td>CGST: </td><td>"+cgst+"</td></tr>\n\
<tr><td>GRAND TOTAL: </td><td>"+gtotal+"</td></tr>\n\
\n\
</table></html>";
return html;
}
});
This the HTMl
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create New Receipt</h4>
</div>
<div class="modal-body">
<form method="post" action="controller/pdf.php">
<div id="print">
<div class="row">
<div class="col-md-7">
<img src="asset/logo.png" alt="Edumentor">
</div>
<div class="col-md-5">
<p style="font-size:15px;">Head Office: 80 Defence Enclave Delhi-110092
<br>
Tel : +91 9650499917,9650499918 web:wwww.edumentor.co.in
<br>
GST No.07AACCE9830DIZS
</p>
<br>
<p><strong>Receipt Number:</strong>
<?php
$val = getReceiptNum();
echo $val;
?>
</p>
</div>
</div>
<br>
<div id="values">
<div class="row">
<div class="form-inline">
<div style="text-align:right;" class="col-sm-8">
<label for="centre">Centre: </label>
<input name="center" id="centre" type="text" class="form-control" name="centre">
</div>
<div class="col-sm-4">
<label for="date">Dated:</label>
<input id="dated" name="dated" type="date" class="form-control" name="date">
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label for="pcentre">Payment Centre:</label>
<input name="payment" id="payment" type="text" class="form-control" name="pcentre">
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group">
<div class="col-sm-12">
<label for="stuname">Student Name:</label>
<input name="studname" id="stuname" type="text" class="form-control" name="stuname">
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-inline">
<div class="col-sm-12">
<div class="col-sm-6">
<label for ="stucont">Contact Number:</label>
<input name="cnum" id="cnum" type="text" class="form-control" name="stucont">
</div>
<div class="col-sm-6">
<label for="stupcont">Parental Contact:</label>
<input name="pnum" id="pnum" type="text" class="form-control" name="stupcont">
</div>
</div>
</div>
</div>
<br>
<table class="table table-bordered">
<tbody>
<tr>
<td>
<div class="form-inline">
<label for="sfees">Sum of Rupees(In Words)</label>
<input name="sum" id="sum" type="text" class="form-control" name="sfees" size="30">
</div>
</td>
<td>
<div class="form-inline">
<label for="">Total Amount :</label>
<input name="amt" id="amt" type="number" name="snumfees" class="form-control" size="10" placeholder="Enter Amount">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="col-sm-12">
<label>Paid by: </label>
<label class="radio-inline"><input id="cash" value="cash" type="radio" name="optradio">Cash</label>
<label class="radio-inline"><input id="cheque" type="radio" value="cheque" name="optradio">Cheque</label>
</div>
<div class="col-sm-4">
<input name="chnum" id="chnum" type="text" name="cheqno" class="form-control" placeholder="Enter cheque number">
</div>
<div class="col-sm-4">
<input name="chdate" id="chdate" type="date" name="cheqdate" class="form-control" placeholder="Enter cheque date">
</div>
<div class="col-sm-4">
<input name="chbank" id="chbank" type="text" name="cheqbank" class="form-control" placeholder="Enter cheque bank">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-inline">
<label for="cname">Course Name:</label>
<input name="course" id="course" type="text" name="cname" class="form-control" placeholder="Enter Course name">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-inline">
<label for="tutfees">Tution Fees:</label>
<input name="tfees" id="tfees" type="text" name="tutfees" class="form-control" readonly>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-inline">
<label for="stax">SGST:</label>
<input name="sgst" id="sgst" type="number" name="stax" class="form-control" readonly>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-inline">
<label for="ctax">CGST:</label>
<input name="cgst" id="cgst" type="number" name="ctax" class="form-control" readonly>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-inline">
<label for="gtfees">Grand Total:</label>
<input name="gtotal" readonly id="gtotal" type="number" name="gtfees" placeholder="Enter total fees" class="form-control">
</div>
</td>
</tr>
</tbody>
</table>
</div>
<br>
<div><p><strong>Terms and Condition:</strong></p>
<br>
<p style="font-size:small; width:120%;margin-top:-4%;">
1.Any fees once paid shall not be refunded under any circumstances.<br>
2.We do not disclose any personal information of student before or after the announcement of the result.<br>
3.In case the cheque bounces, the student is liable to pay ₹500/- extra and deposit whole amount in cash within next 24-48 hours.<br>
4.In case of delay of installment from the due date, penalty # ₹250/- per day will be charged from the student.<br>
5.Tution fee inclusive of GST.<br>
6.All disputes are subject to exclusive juridsiction of Delhi Courts only.<br>
7.All cheque are to be drawn in favour of '<strong>Edumentor Educational Services Pvt. Ltd</strong>.'
</p>
</div>
I agree to the above terms and conditions
<br><br><br><br><br>
<div class="row">
<div class="col-md-8">
<label>Parents/Student Signature</label>
</div>
<div style="text-align:right;" class="col-md-4">
<label>Authorised Signatory</label>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-danger" name="pdf" id="pdf" value="Export To Pdf"/>
<button type="button" class="btn btn-primary" id="btnPrint" name="subPrint">PRINT</button>
<button type="button" class="btn btn-default" onclick="js:window.print()">print modal content</button>
<button type="button" class="btn btn-primary" id="submit">Submit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
Download printThis.js from the following link and include it in your html: https://github.com/jasonday/printThis/blob/0a7f799693af8a8303bf0b8df0efc80c2694af81/printThis.js
Wrap the content you want to print with the following div. Everything outside of this div will not be printed.
<div id="modalDiv">
..content to print..
</div>
Call the following jquery to print all the content including the content that is not viewable. You may include your css files in an array if you have multiple css files.
$("#modalDiv").printThis({
debug: false,
importCSS: true,
importStyle: true,
printContainer: true,
loadCSS: "../css/style.css",
pageTitle: "My Modal",
removeInline: false,
printDelay: 333,
header: null,
formValues: true
});

Multiple two inputs and the inputs generated dynamically by jQuery

I have this form and this is my layout:
I want when the user enters the quantity the total input = qty*price.
My view
<?php $form=array('id'=>'myform');?>
<?php echo form_open('Order/submit',$form);?>
<div class="panel panel-default">
<div class="panel-heading">Customer Details</div>
<div class="panel-body">
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="invoice_number" placeholder="Invoice Number"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="branch" placeholder="Branch"/>
</div>
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term"">
<option value="cash">Cash</option>
<option value="bank">Bank</option>
<option value="other">Other</option>
</select>
</div>
</div><!--customer panel-Body-->
<div class="panel-heading">Invoice Details
</div>
<div class="panel-body">
<div id="education_fields">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option></option>
<?php
foreach($order as $row):
echo"<option data-price='$row->p_price' value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control qty" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control total" name="total[]" value="" placeholder="Total">
<div class="input-group-btn">
<button class="btn btn-success" type="button" onclick="education_fields();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="panel-footer"><small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another product field :)</small>, <small>Press <span class="glyphicon glyphicon-minus gs"></span> to remove the last product :)</small></div>
</div>
<button type="submit" class="btn btn-primary center-block">Checkout</button>
<?php echo form_close();?>
This is my first jQuery and that used to generate a new row by + button
<script>
var room = 0;
function education_fields() {
room++;
var objTo = document.getElementById('education_fields');
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass"+room);
var rdiv = 'removeclass'+room;
var medo='<div class="col-sm-3 nopadding"><div class="form-group"><select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]"><option></option><?php foreach($order as $row){ ?><option data-price="<?php echo$row->p_price;?>" value ="<?php echo $row->p_id; ?>"><?php echo $row->p_name; ?></option><?php } ?></select></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity"></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control price" name="price[]" value="" placeholder="Price"></div></div><div class="col-sm-3 nopadding"><div class="form-group"><div class="input-group"> <input class="form-control" name="total[]" placeholder="Total"/><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_education_fields('+ room +');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div><div class="clear"></div>';
divtest.innerHTML = medo;
objTo.appendChild(divtest);
$('select').selectpicker();
}
function remove_education_fields(rid) {
$('.removeclass'+rid).remove();
}
</script>
and this 2nd jQuery used to get product price from from drop-menu attributes and add that into price input.
<script>
function set_price( slc ) {
var price = slc.find(':selected').attr('data-price');
slc.parent().parent().next().next().find('.price').val(price);
}
$('#education_fields').on('change','select.selectpicker',function(){
set_price( $(this) );
});
</script>
var sample = $('#sample').html();
$('#sample').on('click', '.generate', function() {
$('#sample').append(sample);
});
$('#sample').on('change', 'select.selectpicker', function () {
// keyword this is your current select element
var select = $(this);
// each group of inputs share a common .form element, so use that to
// look up for closest parent .form, then down for input[name="price[]"]
// and set the input's value
select.closest('.form').find('[name^=price]').val(
select.find('option:selected').data('price')
// trigger input's keyup event (*)
).keyup();
});
// (*) note: input[type=text]'s onchange event triggers only after it loses focus; we'll use keyup event instead
// create onkeyup event on the qty and price fields
$('#sample').on('keyup', '[name^=qty], [name^=price]', function() {
// get related form
var form = $(this).closest('.form');
// get its related values
var qty = parseInt(form.find('[name^=qty]').val(), 10),
price = parseInt(form.find('[name^=price]').val(), 10);
// ensure only numbers are given
if (!isNaN(qty) && !isNaN(price)) {
// set the total
form.find('[name^=total]').val(qty * price);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample">
<!-- group all related blocks into a div .form -->
<!-- it makes it easier to reference in your JS -->
<div class="form">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option data-price=200 value=1>tes1</option>
<option data-price=218 value=2>tes2</option>
<option data-price=80 value=3>tes3</option>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control " name="total[]" value="" placeholder="total" readonly>
</div>
</div>
</div>
<button class="generate" type="button">Generate New Form</button>
</div>
Note, that I am lazy instead of doing [name="price[]"], I simply did [name^=price].
Edit changed onchange to keyup.

Categories

Resources