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();
});
Related
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).
I'm writing a program to add tests, exams, practicals, assignments to a module.
With regards to the course weighting I was wondering if you could dynamically change the value of the total weighting when a user enters a weighting per task.
Like this:
Problem
The inputs in the red rectangle should be added up and displayed in the blue rectangles label.
In turn, the blue rectangle should be added up and displayed in the green rectangles label.
Any help will be appreciated please
I have tried this so far:
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="fnum" size="35" id="first">
+ Second Number:
<input type="text" name="snum" size="35" id="sec">
+ Third Number:
<input type="text" name="lom" size="35" id="third3">
<br>
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<button type="button" onclick="Calculate();">Calculate</button>
<script lang="javascript">
function Calculate() {
var first = document.getElementById('first').value;
if(document.getElementById('sec'))
{
var last = document.getElementById('sec').value;
}
else
{
var last = 0;
}
if(document.getElementById('third'))
{
var third = document.getElementById('third').value;
}
else
{
var third = 0;
}
document.getElementById('ans').value = parseInt(first) + parseInt(last) + parseInt(third);
document.form1.submit();
}
https://jsfiddle.net/www1fxjb/9/
What I am asking is to change the label as soon as the numbers change in the input fields.
You need to use the onchangeevent in your input fields properties.
You can then point your onchangeevent to your calculate method.
Also, add default values of "0" in your input fields so that it will always have a value to add and this will prevent errors.
<input type="number" name="fnum" size="35" id="first" onchange="Calculate();" value="0"/>
+ Second Number:
<input type="number" name="snum" size="35" id="second" onchange="Calculate();" value="0"/>
+ Third Number:
<input type="number" name="lom" size="35" id="third" onchange="Calculate();" value="0"/>
<br />
Answer:
<input type="text" name="ans" size="35" id="ans" />
Javascript:
<script lang="javascript">
function Calculate() {
if (document.getElementById('first')) {
var first = document.getElementById('first').value;
}
else {
var first = 0;
}
if (document.getElementById('second'))
{
var second = document.getElementById('second').value;
}
else
{
var second = 0;
}
if (document.getElementById('third'))
{
var third = document.getElementById('third').value;
}
else
{
var third = 0;
}
document.getElementById('ans').value = parseInt(first) + parseInt(second) + parseInt(third);
document.form1.submit();
}
</script>
Hope it helps.
I want to add values by clicking the value buttons by each and every by the following function
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var txtThirdNumberValue = document.getElementById('txt3').value;
var txtFourthNumberValue = document.getElementById('txt4').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
var result = parseInt(txtFirstNumberValue) + parseInt(txtThirdNumberValue);
var result = parseInt(txtFirstNumberValue) + parseInt(txtFourthNumberValue);
if (!isNaN(result)) {
document.getElementById('txt1').value = result;
}
}
// Here I gave the other two events to add to the text field by the id names
<!-- here I gave the three Value buttons and on click function -->
<input type="text" id="txt1" value="10" />
<input type="button" id="txt2" value="10" onClick="sum();" />
<input type="button" id="txt3" value="20" onClick="sum();" />
<input type="button" id="txt4" value="30" onClick="sum();" />
You can get the value of the button by passing this.value to the onClick function where this represent the element itself.
function sum(value) {
document.getElementById('txt1').value = Number(document.getElementById('txt1').value) + Number(value);
}
<input type="text" id="txt1" value="10" />
<input type="button" id="txt2" value="10" onClick="sum(this.value);" />
<input type="button" id="txt3" value="20" onClick="sum(this.value);" />
<input type="button" id="txt4" value="30" onClick="sum(this.value);" />
This javascript will help you.
<script>
function sum(e) {
var result = parseInt(e.value) + parseInt(document.getElementById('txt1').value);
if (!isNaN(result)) {
document.getElementById('txt1').value = result;
}
}
</script>
I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>
You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});
Here is my form
<form method="post" action="collect_vals.php">
<div id="input_fields">
<div><input type="text" placeholder="unit" name="unit[]"> <input type="text" placeholder="price" name="price[]"><input type="text" placeholder="total" name="total[]"> <span class="fa fa-plus-circle" id="add_field"></span></div>
</div>
<input type="submit" value="submit">
</form>
https://jsfiddle.net/d9bhsL4o/1/
Here is my script:
<script type="text/javascript">
$(document).ready(function() {
$("input[name=unit]").keyup(function() {
var unit = new Array();
var qty = new Array();
$("input[name=unit]").each(function() {
unit.push($(this).val());
});
$("input[name=qty]").each(function() {
qty.push($(this).val());
});
var total = new Array();
for (var i = 0; i <unit.length; i++) {
var inp=unit[i]*qty[i];
("total["+i+"].value="+inp.value);
}
});
});
</script>
Trying to multiply two values and keep on third. Does not working. What the wrong with the code
Am attached class definition inside html both rendered and appended element. I tweak around your html code and use this to total up all values respectively :
HTML
<input type="text" placeholder="unit" name="unit[]" class="a">
<input type="text" placeholder="price" name="price[]" class="a">
<input type="text" placeholder="total" name="total[]" class="total">
JS
......
......
$("#input_fields").append('<input type="text" placeholder="unit" name="unit[]" class="a">
<input type="text" placeholder="price" name="price[]" class="a">
<input type="text" placeholder="total" name="total[]" class="total">
<span id="remove" class="fa fa-minus-circle"></span</div>');
......
......
// capture both unit AND price keyup
$("#input_fields").on('keyup', '.a', function () {
// add current keyup textbox also into stack
var all = $(this).siblings('input.a').addBack();
var sum = 1;
// loop over those element
all.each(function(i,e){
// sum both values
sum *= $(e).val();
});
// finally filtered textbox with total class
// and assign the output
$(this).nextAll('.total').val(sum);
});
DEMO
You should traverse the DOM, there are multiple ways to travese DOM. Here I have used .siblings() to get total and qty
$("#input_fields").on('keyup', "input[name='unit[]']", function () {
var unit = $(this).val();
var price = $(this).siblings("input[name='price[]']").val();
$(this).siblings("input[name='total[]']").val(unit * price);
});