How can I sum multiple Numeric textbox value? - javascript

I have multiple Numeric textbox as shown below in the snippet, all are currency format textbox's. How can I sum the values of textboxes in Class Name Charges and display the total sub-total-Of-Charges textbox and subtract if any value in textbox's with class=sub from sub-total-Of-Charges textbox value.
I have used the following jQuery Code which is working but two problems.
Doesn't Keep the currency format
the value of net-invoiced-amount is updated only when I update textbox value in textbox class .sub same thing .sub-total-Of-Charges value is updated on .Charges are updated but I need to re-calculate or update the value net-invoiced-amount or .sub-total-Of-Charges whenever .sub or .charges textbox's values are changed.
$(document).ready(function () {
$(document).on("change", ".charges", function () {
var calculated_total_sum = 0;
$(".charges").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$(".sub-total-Of-Charges").val(calculated_total_sum);
});
$(document).on("change", ".sub", function () {
var netInvoicedAmount = $(".sub-total-Of-Charges").val();
$(".sub").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
netInvoicedAmount -= parseFloat(get_textbox_value);
}
});
$(".net-invoiced-amount").val(netInvoicedAmount).trigger("change");
});
});

You need to get reference of textbox where you need to set the updated value using data("kendoNumericTextBox") and then set new value using .value("newwvalue") this will update new value according to the format which you have set earlier .
Also , use $(this).attr("aria-valuenow") to get the original value of textbox without any currency and change your selector to $(".k-formatted-value.charges") to get only input value from particular textbox .Currently , when you will inspect html generated it has 2 input box with same class that's the reason total sum is not working.
Demo Code :
$("#TotalDirectLaborCharges, #TotalIndirectLaborCharges, #TotalContractCharges, #TotalTravelCharges, #TotalAdjustments, #TotalAdjustments, #CostsAlreadyPaid, #Other, #NetInvoicedAmount ,#SubtotalOfCharges").kendoNumericTextBox({
decimals: 2,
format: "c"
});
//add both selector
$(document).on("change", ".charges,.sub", function() {
var calculated_total_sum = 0;
$(".k-formatted-value.charges").each(function() {
//get original value without currecny
var get_textbox_value = $(this).attr("aria-valuenow");
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
//get kendo textbox
var numerictextbox = $("#SubtotalOfCharges").data("kendoNumericTextBox");
//set value
numerictextbox.value(calculated_total_sum);
});
//add both selector
$(document).on("change", ".sub ,.charges", function() {
//get value from inputbox
var netInvoicedAmount = $("#SubtotalOfCharges").data("kendoNumericTextBox").value();
$(".k-formatted-value.sub").each(function() {
//get original value
var get_textbox_value = $(this).attr("aria-valuenow");
if ($.isNumeric(get_textbox_value)) {
netInvoicedAmount -= parseFloat(get_textbox_value);
}
});
//set value in invoice amt
var numerictextbox = $("#NetInvoicedAmount").data("kendoNumericTextBox");
numerictextbox.value(netInvoicedAmount);
});
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.3.1021/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.3.1021/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.3.1021/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2020.3.1021/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2020.3.1021/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2020.3.1021/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2020.3.1021/js/kendo.all.min.js"></script>
<div class="quarter m-l-lg m-y text-right">
<label class="m-r-lg required" asp-for="TotalDirectLaborCharges">Total Direct Labor Charge<br /></label>
<input id="TotalDirectLaborCharges" class="charges" /><br />
<label class="m-r-lg required" asp-for="TotalIndirectLaborCharges">TotalIndirectLaborCharges<br /></label><br />
<input id="TotalIndirectLaborCharges" class="charges" /><br />
<label class="m-r-lg required" asp-for="TotalContractCharges">TotalContractCharges</label><br />
<input id="TotalContractCharges" class="charges" /><br />
<label class="m-r-lg required" asp-for="TotalTravelCharges">TotalTravelCharges</label><br />
<input id="TotalTravelCharges" class="charges" /><br />
<label class="m-r-lg required" asp-for="TotalAdjustments">TotalAdjustments</label><br />
<input id="TotalAdjustments" class="sub" /><br />
<label class="m-r-lg required" asp-for="CostsAlreadyPaid">CostsAlreadyPaid</label><br />
<input id="CostsAlreadyPaid" class="sub" /><br />
<label class="m-r-lg required" asp-for="Other">Other</label><br />
<input id="Other" class="sub" /><br />
<label class="m-r-lg required" asp-for="SubtotalOfCharges">SubtotalOfCharges</label><br />
<input id="SubtotalOfCharges" readonly class="sub-total-Of-Charges" />
<br />
<label class="m-r-lg required" asp-for="Other">NetInvoicedAmount</label><br />
<input id="NetInvoicedAmount" readonly class="netInvoicedAmount" />
</div>

As you've used jQuery for your project, I'm also writing this answer using the library.
$(document).ready(function() {
let $references = {
subtotal: $('#SubtotalOfCharges').first(),
net: $('#NetInvoicedAmount').first(),
fields: {
subtract: $('input.sub'),
charge: $('input.charges')
}
}
function calculateSum($elements) {
return Array.from($elements).reduce((previousValue, element) => {
val = $(element).val();
if(val)
previousValue += parseFloat($(element).val());
return previousValue;
}, 0)
}
$(document).on('change', 'input', function() {
let sum = {
subtract: calculateSum($references.fields.subtract),
charge: calculateSum($references.fields.charge),
}
$references.subtotal.val(sum.charge);
$references.net.val(sum.charge - sum.subtract);
});
})
input,
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Total Direct Labor Charge</label>
<input id="TotalDirectLaborCharges" class="charges">
<label>TotalIndirectLaborCharges</label>
<input id="TotalIndirectLaborCharges" class="charges">
<label>TotalContractCharges</label>
<input id="TotalContractCharges" class="charges">
<label>TotalTravelCharges</label>
<input id="TotalTravelCharges" class="charges">
<label>TotalAdjustments</label>
<input id="TotalAdjustments" class="sub">
<label>CostsAlreadyPaid</label>
<input id="CostsAlreadyPaid" class="sub">
<label>Other</label>
<input id="Other" class="sub">
<label>SubtotalOfCharges</label>
<input id="SubtotalOfCharges" readonly class="sub-total-Of-Charges">
<label>NetInvoicedAmount</label>
<input id="NetInvoicedAmount" readonly class="net-invoiced-amount">
How does it work?
Instead of manually triggering a change event whenever a .sub (or .charges) is changed, to calculate the subtotal/net amount, you can bind the event handler to both of the input groups and run the calculations once.
I've used $references to tidy up the code a little bit and a reduce function is used to calculate the sum of a field group.
Array.from is used to create a native Javascript array from the jQuery object.
For more information on Array.reduce, visit its documentation here, and for more information on Array.from visit here.
Finally, a feasible solution is to use input prefixes. Every UI framework normally has one built-in, otherwise, you can take a look at Bootstrap's input groups here (Especially, .input-group-prepend).

Related

javascript event handler not working (button click - google says null)

I've looked over a number of threads here of similar problems to little avail - I can't figure out exactly what's going wrong here. Google claims that the element I'm trying to reference is null
Uncaught TypeError: Cannot read property 'addEventListener' of null at sales.js:12
and no matter how I've tried to fix it, it doesn't seem to work. As you can see in the js code, I've tried a number of ways of fixing it based on stuff I've found here.
Originally the <script src ="sales.js"> in the HTML file was up in the head, but I read in some pages here that putting it there can make it load before everything else and to put it down before the HTML closing tag.
Any suggestions?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main>
<h1>Sales Calculator</h1>
<p>Complete the form and click "Calculate".</p>
<fieldset>
<legend>
Item Information
</legend>
<label for="item">Item:</label>
<input type="text" id="item" ><br>
<label for="price">Price:</label>
<input type="text" id="price" ><br>
<label for="discount">Discount %:</label>
<input type="text" id="discount" ><br>
<label for="taxRate">Tax Rate:</label>
<input type="text" id="taxRate" ><br>
<label for="total">Discount Price:</label>
<input type="text" id="discountPrice" disabled ><br>
<label for="salesTax">Sales Tax:</label>
<input type="text" id="salesTax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br><br>
<div id="buttons">
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br></div>
</fieldset>
<pre>© Fall 2020 Rob Honomichl - Dakota State University</pre>
</main>
</body>
<script src="sales.js"></script>
</html>
JS Code:
//"use strict"
var $ = function (id) {
return document.getElementById(id);
};
//window.addEventListener("DOMContentLoaded", () => {
//$("#calculate").addEventListener("click", processEntries);
//});
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("#calculate").addEventListener("click", processEntries);
});
//window.onload = function(){
//$("#calculate").addEventListener("click", processEntries);
//};
const processEntries = () => {
//Gather User Input
//var item = document.querySelector("#item").value;
var price = parseFloat(document.querySelector("#price").value).toFixed(2);
var discount = parseInt(document.querySelector("#discount").value);
var taxRate = parseInt(document.querySelector("#taxRate").value);
//Calculate Discounted Price
function discountPriceCalc(price, discount) {
const disPrice = price * (discount/100);
return disPrice.toFixed(2);
}
//Calculate Sales Tax
function salesTaxCalc(discountPrice, taxRate) {
const taxTotal = price * (taxRate/100);
return taxTotal.toFixed(2);
}
//Calculate Total
function totalCalc(discountPrice, salesTax) {
return ((Number(discountPrice) + Number(salesTax).toFixed(2)));
}
//Calculate the disabled text box values
var discountPrice = discountPriceCalc(price, discount);
var salesTax = salesTaxCalc(discountPrice, taxRate);
var Total = totalCalc(discountPrice, salesTax);
//Update Text Boxes
document.getElementById("discountPrice").value = discountPrice;
document.getElementById("salesTax").value = salesTax;
document.getElementById("total").value = Total;
//set focus to Item box after
document.getElementById("item").focus();
};
You need to get rid of the # in the getElementById call to properly locate the element.
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("calculate").addEventListener("click", processEntries);
});

Array.foreach only gets val() from the last input id with keyup

Please help me figure out why only the last input id gets its value added to the input id= #attr3 with keyup.
I need both inputs in the div to have their values put into the input outside the div separated with a comma(,). i made a fiddle https://jsfiddle.net/dc6v6gjd/1/. Thanks
<div id ="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
$(document).ready(function () {
var text = $("#candy :input").map(function () {
return this.id;
}).get();
var attr = [];
for (i=0; i<text.length; i++) {
attr.push('#'+ text[i]);
}
var mat = attr.join(", ");
$(mat).keyup(function(){
update();
function update() {
attr.forEach(function(index, i){
// alert(i);
$("#attr3").val( $(attr[i]).val() + "," );
});
}
});
});
The reason is you're overriding the value of attr3 on each iteration of forEach. You could instead use join to get the value.
e.g.
function update() {
var val = attr
.map(function(a) {
return $(a).val();
})
.join(",");
$("#attr3").val(val);
}
That being said I'd probably go with a simpler solution like this.
// set the keyup event handler and add all inputs to an array.
var inputs = $("#candy :input").keyup(function() {
update();
}).get();
// read all input values into comma separated string and update attr3
function update() {
var val = inputs.map(function(i) {
return $(i).val();
}).join(",");
$("#attr3").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
Update: Support dynamically added inputs.
$(document).on("keyup", "#candy :input", function() {
update();
});
function update() {
var val = $("#candy :input").get().map(function(i) {
return $(i).val();
}).join(",");
$("#attrFinal").val(val);
}
var count = 3;
$("#add").click(function() {
$("#candy").append("<input type='text' id='attr" + count++ + "' name='emailAddress' />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attrFinal" name="username" value="">
<button id="add">Add New</button>

Getting values from multiple text boxes on keypress in javascript

I have 8 different text fields in my form, it's a part of customer bill.
Here it is
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty">
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation">
......
up to 8
From this I want to show the sum of all the values as total value
<span>Total extra cost:1678</span>
It should be changed when the values of any text field is changed, so how can I do it perfectly using keyup event?
UPDATE
I have attached an onkeyup event to each textfield
`onkeyup="findSum(this.value)"'
and i am using a global array for store the input values var extras=[]
function findSum(value)
{
if(value!=''){
console.log(value);
extras.push(parseInt(value));
if(extras!='')
$('#extratotal').text(extras.reduce(getSum));
else $('#extratotal').text('0');
}
}
But its not worked well
You can get SUM of all inputs that have form-control class on keyup event like this:
$('input.form-control').on('keyup',function() {
var total = 0;
$('input.form-control').each(function(){
if (this.value == ''){
total += parseInt(0);
}else{
total += parseInt(this.value);
}
});
$('#total').val(total);
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty" >
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation" >
<input type="text" name="other" class="form-control" placeholder="other" >
Total extra cost: <input id="total" >
You can use the target.value property of the event passed to the key listener - this will give you the value of the input field:
document.addEventListener('input', 'keyup', function(e) {
// use e.target.value here
}
Just add this to a running total and update the text inside the listener function.
I have defined in JavaScript instead of jQuery. Try it..
<script>
function sum()
{
var sum = 0;
var array_field = document.getElementsByClassName('sum_field');
for(var i=0; i<array_field.length; i++)
{
var value = Number(array_field[i].value);
if (!isNaN(value)) sum += value;
}
document.getElementById("total").innerHTML = sum;
}
</script>
<body>
<input type="text" name="txtcustomduty" class="form-control sum_field" placeholder="Customs Duty" onkeyup="sum()">
<input type="text" name="txtlcltranspotation" class="form-control sum_field" placeholder="Local Transportation" onkeyup="sum()">
<p>Total:<span id="total">0</span></p>
</body>

Extract Unique Element ID using Javascript

Okay, so I have a form which adds an item to a list of items and does calculations with it, but every new item thats added is done on the users side before being submitted to the server for verification and updating of database. Now, I've looked at other answers and couldnt really get an answer. If the user adds a new item and enter a quantity and rate it should calculate the amount automatically, how would one extract the unique ID identifier to change the value of the amount? The code below and in this case the unique identifier is 19786868. The length of this identifier is always different and their is no unique pattern, the length and value is generated by a random command.
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
How would I extract this unique identifier with the OnChange command in JavaScript to calculate the amount value?
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
var id = el.id.replace(/\D+/g,"");
console.log( id ); // "19786868"
});
so basically use a this.id.replace(/\D+/g,"") where all non Digit \D gets replaced by ""
Here's an example using the input event:
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
el.addEventListener("input", function() {
var id = this.id.replace(/\D+/g,"");
alert( id );
}, false)
});
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_123_foobar" />
Take note that: asd_123_foo_9 will return 1239 as result so make sure to always have asd_123_foo as ID value
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" onchange="extractId(event);"/>
And in javascript :
function extractId(event) {
var elem = event.target;
var myArr = elem.id.split('_');
var yourUnique_id = myArr[3];
}
To be able to respond to newly added input controls, you need to capture the change event at some parent element, otherwise you will not trap the change on newly added elements.
Here is some code that handles the change event on the document. As this event bubbles up, it will eventually get there, so we can respond to it:
For extracting the number from the input's id, we can use a regular expression:
document.onchange = function(e) {
var match = e.target.id.match(/^(list_item_attributes_.*?_)(rate|quantity)$/);
if (!match) return; // not rate or quantity
// read rate and quantity for same ID number:
var rate = +document.querySelector('#' + match[1] + 'rate').value;
var quantity = +document.querySelector('#' + match[1] + 'quantity').value;
// write product as amount:
document.querySelector('#' + match[1] + 'amount').value = rate*quantity;
}
Quantity: <input class="form-control" type="text" id="list_item_attributes_19786868_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_19786868_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_19786868_amount" /><br>
<p>
Quantity: <input class="form-control" type="text" id="list_item_attributes_14981684_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_14981684_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_14981684_amount" /><br>
As you have asked to respond to the change event, I have kept it that way, but you might be interested to use the input event instead, which will trigger as soon as any character changes in an input.
The above sample does not protect the amount fields from input. You should probably do something about that, because users could just overwrite the calculated result.
document.querySelector(".my-form").addEventListener("change", function(e) {
var changed = e.target;
var matchedId = changed.id.match(/^(list_item_attributes_[^_]*)_/);
if (!matchedId) {
// this isn't one of the relevant fields
return;
}
var uniquePrefix = matchedId[1];
var quantity = document.querySelector("#" + uniquePrefix + "_quantity");
var rate = document.querySelector("#" + uniquePrefix + "_rate");
var amount = document.querySelector("#" + uniquePrefix + "_amount");
var newVal = quantity.value * rate.value;
if (isNaN(quantity.value) || isNaN(rate.value) || isNaN(newVal)) {
amount.value = "";
} else {
amount.value = newVal;
}
});
<form class="my-form">
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</form>
If the user adds a new item and enter a quantity and rate it should
calculate the amount automatically, how would one extract the unique
ID identifier to change the value of the amount?
You can use input event; for loop; attribute contains selector [attributeName*=containsString], .nextElementSibling, .previousElementSibling, to sum values of id containing "quantity" and id containing "rate" and set result at id containing "amount"
function calculate() {
this.parentElement.querySelector("[id*=amount]")
.value = +this.value
+ +(/quantity/.test(this.id)
? this.nextElementSibling
: this.previousElementSibling
).value
}
var elems = document.querySelectorAll("[id*=quantity], [id*=rate]");
for (var i = 0; i < elems.length; i++) {
calculate.call(elems[i]); elems[i].oninput = calculate;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" value="1" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" value="2" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</div>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786867_quantity" value="3" />
<input class="form-control" type="text" id="list_item_attributes_19786867_rate" value="4" />
<input class="form-control" type="text" id="list_item_attributes_19786867_amount" />
</div>

Passing values in Javascript/Jquery

I have Jquery/Javascript function which calculates certain field values. One of the field returns a value in
function calcTotals() {
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
}
I have another function with a checkbox
function recalcTotal() {
var total12 = 0;
$('input:checked').each(function () {
total12 += $(this).marginObj.value;
});
$('#total12').val(total12);
}
$("input[type='checkbox']").on("click", function () {
recalcTotal();
});
I need to pass the values from the marginObj.value to the next function that is total12 += $(this).marginObj.value; What iam trying to achieve is iam taking the values from marginObj.value and there is a checkbox, if i check the checbox it totals all the checked values and show it in grandTotal field.
<input name="grandTotal" id="total12" readonly/>
Please check the complete script.
FIDDLE
So what i want is there are some values in Margin with a checkbox. When i check any checkbox, its should total the selected checkboxes and show in the Grand Total field.
I am guessing the issue is getting the marginObj which is an input element after check box.
$(function () {
recalcTotal();
$("input[type='checkbox'").on("click", function () {
recalcTotal();
});
function recalcTotal() {
var total = 0.0;
$("input:checked").each(function () {
total += $(this).next("input").val() * 1.0;
});
$("#total").val(total.toFixed(3));
}
});
<input type="text" id="total" readonly/> <br />
<input type="checkbox" name="values"/><input type="text" readonly value="1"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="2"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="3"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="4"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="5"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="6"/> <br />
Not 100% what you are asking, but if you are simply trying to pass a value from one function to another, there are multiple approaches, but the simplest is to pass arguments to the function.
//this function supports 1 argument
function calcTotals( amount ) {
//add 1 and return
return amount + 1;
}
//calling this argument
var amount = 5;
var newAmount = calcTotals( amount );
assuing marginObj is globally accessible.
function recalcTotal() {
var total12 = 0;
$('input:checked').each(function () {
total12 += $(this).marginObj.value;
});
$('#total12').val(total12);
}
$("input[type='checkbox']").on("click", function () {
calcTotals(); -- will populate marginObj.value
recalcTotal();
});

Categories