calculating the sum of the array form with javascript - javascript

I want to display the number of values ​​in array form. I have a lot of form with only one name is "price []" and have each value on the form. I want to calculate the total value of the form "price []". I'm still a beginner in javascript. and I want to calculate it by using javascript. The following coding that I have made.
<html>
<body>
<form id="hitung" name="hitung">
price 1 <input type="text" name="price[]" class="price" value="1000"/><br>
price 2 <input type="text" name="price[]" class="price" value="3000"/><br>
price 3 <input type="text" name="price[]" class="price" value="2000"/><br>
price 4 <input type="text" name="price[]" class="price" value="1000"/><br>
price 5 <input type="text" name="price[]" class="price" value="3000"/><br><br>
total <input type="text" name="total" class="total"/>
</form>
</body>
</html>
and I want to ask you again, if there is a new input from the outside, then the total will also be changed directly. how to do it. help me please. thank you

Here's an example: http://jsfiddle.net/c4UyA/1/
var sum = 0;
$("form > input[name='price[]']").each(function() {
$this = $(this);
sum += parseInt($this.attr("value"));
});
$("form > input[name='total']").attr("value", sum);

Related

Not getting total value of input tags

Why my codes is not getting the total value of each row?, its getting only the first row value.
tried to insert it into .each function, but its not functioning
function calc_total()
{
total=0;
$('#po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
}
get the grand total of each rows.
You need to select your inputs differently so you can add their total. Id's must be unique so it won't let you .each a single element. If you give them each a class with the same name you can do it like this:
var total = 0;
$('.po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="4">
<input type="input" class="po_total_amount" value="90">
<input type="input" id="totalPrice">

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

How to calculate form fields values to update hidden field value?

I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance
This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">
You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />
Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text
I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.
if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

Javascript - decimal format

Edit: this isn't a math or operators question (I don't think). This is a formatting or masking question.
Creating an order form. I have Javascript that tallies/totals each column and displays the quantity and column cost in two other fields. I would like for the column cost to be formatted with a decimal and 2 values after it, but can't seem to figure it out. .toFixed(2) doesn't seem to work (because it's a string?) and I'm wondering if it's because the quantity and cost fields are readonly?
I'm stuck.
//example of tallying one column
<input type="number" min="0" value="0" name="proA#x#" class="input-mini proA qty1 coffee total">
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total1").val(sum);
$(".cost1").val(sum*9.00);
});
//item tally
<input type="number" id="D1" name="D1" class="input-mini uneditable-input total1" placeholder="0" readonly>
//item cost
<input type="number" id="" name="" class="input-mini uneditable-input cost1" placeholder="x 9.00" readonly >
Thanks in advance!
I would do it this way
var sum = 0.00;
$(".qty1").each(function(){
sum += parseFloat($(this).val());
});
$(".cost1").val(sum.toFixed(2));

multiply form values from form array with JS

I have html form with arrays:
<form method="post" id="formaa" name="form">
<div id="fields">
<div id="divas1" class="row">
<img src="d.jpg" /><a href="#" id="uid1" onClick="u(this);">
<img src="u.jpg" /></a><input type="text" name="ite[]" id="item" /><input type="text" name="q[]" id="quantity" class="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" class="kaina" onkeyup="update();"/><input type="text" name="sum[]" id="suma" size="10" disabled="disabled"/></div>
</div>
<br />
<input type="button" name="nw" id="new" value="ADD" onClick="naujas('laukeliai');" /><br />
Total: <input type="text" name="sumaa[]" id="suma" size="10" disabled="disabled"/>
</form>
Each time I push forms ADD button, inside the <div id="fields"> is included new div block <div id=divas(i++)> I need multiply qp[] and pr[] values and dynamicaly add to sum field, need do multiply price and quantity of each product seperately and get final each product price (not all products total).
first tried to get all values and filter these two, but couldnt figure out...
var form = document.getElementsByName('form')[0];
var inputs = form.getElementsByTagName('input');
for (var i = 0, j = inputs.length; i < j; i++) {
var element = inputs[i];
alert(element.value);
}
How to extract from this array only needed values and multiply? Thanks for advices.
Assuming you want to generate the sum of the prices for all the products and quantities you bought, you would first rewrite your HTML as:
<form id="example_form">
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<!-- ... many more rows -->
<input type="text" disabled id="sum" name="sum"></input>
</form>
Use jQuery to make field access easier. Using JQuery, you would use the following JS:
function update() {
var total = 0;
$("#example_form div.row").each(function(i,o){
total += $(o).find(".quant").val() *
$(o).find(".price").val();
});
$("#example_form #sum").val(total);
}
This will update totals for you. To do this each time any number is changed, you would need to register it with the corresponding fields, using something like
$("#example_form div.row input").change(update);
Have I convinced you of using JQuery? See it working at http://jsfiddle.net/UnYJ3/2/
you can read form array in way as below
frmRefer = document.getElementByTagName("form")[0];
for(i= 0 ; i<frmRefer.elements["ite[]"].length;i++){
alert(frmRefer.elements["ite[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["quant[]"].length;i++){
alert(frmRefer.elements["quant[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["pr[]"].length;i++){
alert(frmRefer.elements["pr[]"][i].value );
}

Categories

Resources