I'm trying to get the total amount from input value with pure JavaScript but It's returning blank. The format of the amount value for each input is as follow 0.00
PHP
//rest of code
$i = 0;
while ($row = mysqli_fetch_array($result)) {$i++;
<input id="Amount'.$i.'" name="Amount" value="'.$plan['price'].'" type="text">
}
echo ' <input id="total" name="finalResult" value="" type="text">';
JS
function totalResult(){
var arr = document.getElementsByName('Amount');
var total=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
total += parseInt(arr[i].value);
}
document.getElementById('total').value = total;
}
Use HTML5's query selctor API querySelectorAll() like the following:
function totalResult(){
var arr = document.querySelectorAll('input[name=Amount]');
var total=0;
arr.forEach(function(item){
if(parseInt(item.value))
total += parseInt(item.value);
});
document.getElementById('total').value = parseFloat(total).toFixed(2);
}
totalResult();
<input id="Amount1" name="Amount" value="10.00" type="text" />
<input id="Amount2" name="Amount" value="20.00" type="text" />
<input id="Amount3" name="Amount" value="30.00" type="text" /><br>
Result:
<input id="total" name="finalResult" value="" type="text">
Related
I am trying to create a javascript that calculates the sum of 4 amounts, that is generated from the input fields.
The problem is, I want the Total Invoice Value to start reflecting the value after the user has inputted the Rate 1 and Amount 1 has shown. But it doesnt happen until all the 4 amounts have been generated. The Total Invoice Value reflect only after I input the amount in Rate 4.
The complete code I am working with right now is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="register" id="myForm" enctype="multipart/form-data" action="register" method="POST">
Qty 1:<input type="number" step="any" name="Qty1" autocomplete="off" id="Qty1" required><br>
Rate 1:<input type="number" step="any" name="Rate1" autocomplete="off" id="Rate1" class="rate" required><br>
Amount 1:<input readonly type="number" step="any" name="Amt1" autocomplete="off" id="Amt1" required><br><br>
Qty 2:<input type="number" step="any" name="Qty2" autocomplete="off" id="Qty2" required><br>
Rate 2:<input type="number" step="any" name="Rate2" autocomplete="off" id="Rate2" class="rate" required><br>
Amount 2:<input readonly type="number" step="any" name="Amt2" autocomplete="off" id="Amt2" required><br><br>
Qty 3:<input type="number" step="any" name="Qty3" autocomplete="off" id="Qty3" required><br>
Rate 3:<input type="number" step="any" name="Rate3" autocomplete="off" id="Rate3" class="rate" required><br>
Amount 3:<input readonly type="number" step="any" name="Amt3" autocomplete="off" id="Amt3" required><br><br>
Qty 4:<input type="number" step="any" name="Qty4" autocomplete="off" id="Qty4" required><br>
Rate 4:<input type="number" step="any" name="Rate4" autocomplete="off" id="Rate4" required><br>
Amount 4:<input readonly type="number" step="any" name="Amt4" autocomplete="off" id="Amt4" required><br><br>
Total Invoice Value:<input readonly type="number" step="any" name="TotalInvoiceValue" id="TotalInvoiceValue" pattern=".{1,}" autocomplete="off" required><br>
</form>
<script>
$('#Rate1').keyup(function(){
var Qty1;
var Rate1;
textone = parseFloat($('#Qty1').val());
texttwo = parseFloat($('#Rate1').val());
var result = textone * texttwo;
$('#Amt1').val(result.toFixed(2));
});
$('#Rate2').keyup(function(){
var Qty2;
var Rate2;
textone = parseFloat($('#Qty2').val());
texttwo = parseFloat($('#Rate2').val());
var result = textone * texttwo;
$('#Amt2').val(result.toFixed(2));
});
$('#Rate3').keyup(function(){
var Qty3;
var Rate3;
textone = parseFloat($('#Qty3').val());
texttwo = parseFloat($('#Rate3').val());
var result = textone * texttwo;
$('#Amt3').val(result.toFixed(2));
});
$('#Rate4').keyup(function(){
var Qty4;
var Rate4;
textone = parseFloat($('#Qty4').val());
texttwo = parseFloat($('#Rate4').val());
var result = textone * texttwo;
$('#Amt4').val(result.toFixed(2));
});
$('#Rate4').keyup(function(){
var Amt1;
var Amt2;
var Amt3;
var Amt4;
textone = parseFloat($('#Amt1').val());
texttwo = parseFloat($('#Amt2').val());
textthree = parseFloat($('#Amt3').val());
textfour = parseFloat($('#Amt4').val());
var result = textone + texttwo + textthree + textfour;
$('#TotalInvoiceValue').val(result.toFixed(2));
});
</script>
I tried to get the javascript to start taking totals from rate 1 itself by adding multiple element name in the #TotalInvoiceValue function like this:
$('#Rate1, #Rate2, #Rate3, #Rate4').keyup(function(){
var Amt1;
var Amt2;
var Amt3;
var Amt4;
textone = parseFloat($('#Amt1').val());
texttwo = parseFloat($('#Amt2').val());
textthree = parseFloat($('#Amt3').val());
textfour = parseFloat($('#Amt4').val());
var result = textone + texttwo + textthree + textfour;
$('#TotalInvoiceValue').val(result.toFixed(2));
});
But it still doesn't work.
I also tried assiging same class to all the Rate inputs like this:
html
<input id="Rate1" class="rate" type="text">
<input id="Rate2" class="rate" type="text">
<input id="Rate3" class="rate" type="text">
<input id="Rate4" class="rate" type="text">
javascript
$('.rate').on('keyup', function() {
let result = 0;
$('.rate').each(function() { result += parseFloat(this.value); });
$('#TotalInvoiceValue').val(result.toFixed(2));
})
And even this is not working for me. Please help.
In the Demo the following was used:
HTMLFormControlsCollection API
<input type="number">
<output></output>
oninput On-event Property
Event Delegation
Note: This is pure JavaScript.
If each input and output element has an initial value:
<input id="N0" type="number" value="0">
...
<input id="N*" type="number" value="0">
<output id="T0">0</output>
Then expressions like this will always be displayed as a number which is important if your event handler listens on an event that has an immediate reaction (ex. input, keypress, etc):
T0.value = N0.valueAsNumber + N1.valueAsNumber + ...N(N).valueAsNumber
Even though the only input the user uses was N0 at the time, N1 thu N(N) is still included in expression because they started off with value="0".
Demo
var sum = document.forms.sum;
var f = sum.elements;
var n0 = f.N0;
var n1 = f.N1;
var n2 = f.N2;
var n3 = f.N3;
var t0 = f.T0;
sum.oninput = add;
function add(e) {
if (e.target.className === "N") {
t0.value = n0.valueAsNumber + n1.valueAsNumber + n2.valueAsNumber + n3.valueAsNumber;
} else {
return false;
}
return false;
}
input {
font: inherit;
display: block;
width: 6ch
}
<form id='sum'>
<input id='N0' type='number' class='N' value='0'>
<input id='N1' type='number' class='N' value='0'>
<input id='N2' type='number' class='N' value='0'>
<input id='N3' type='number' class='N' value='0'>
<output id='T0'>0</output>
</form>
JSFiddle Example
https://jsfiddle.net/o2gxgz9r/47359/
HTML
<div>
Value 1: <input class="val" id="val1">
<br/>
Value 2: <input class="val" id="val2">
<br/>
Value 3: <input class="val" id="val3">
<br/>
Value 4: <input class="val" id="val4">
<br/>
Result: <input class="result">
</div>
JS
$(document).ready(function() {
var handleChange = function() {
var result = 0;
var setResult = true;
$(".val").each(function(){
if($(this).val() > 0) {
result += parseInt($(this).val());
} else {
setResult = false;
}
})
$(".result").val(setResult ? result : '');
};
$(".val").change(handleChange);
});
Thanks for all of your answers. Using your suggestions, this is how my problem got fixed:
HTML:
<form name="register" id="myForm" enctype="multipart/form-data" action="register" method="POST">
Qty :<input type="number" step="any" name="Qty1" autocomplete="off" id="Qty1" required><br>
Rate:<input type="number" step="any" name="Rate1" autocomplete="off" id="Rate1" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt1" autocomplete="off" id="Amt1" class="amt" required><br><br>
Qty :<input type="number" step="any" name="Qty2" autocomplete="off" id="Qty2" required><br>
Rate:<input type="number" step="any" name="Rate2" autocomplete="off" id="Rate2" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt2" autocomplete="off" id="Amt2" class="amt" required><br><br>
Qty :<input type="number" step="any" name="Qty3" autocomplete="off" id="Qty3" required><br>
Rate:<input type="number" step="any" name="Rate3" autocomplete="off" id="Rate3" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt3" autocomplete="off" id="Amt3" class="amt" required><br><br>
Qty :<input type="number" step="any" name="Qty4" autocomplete="off" id="Qty4" required><br>
Rate:<input type="number" step="any" name="Rate4" autocomplete="off" id="Rate4" class="rate" required><br>
Amount :<input readonly type="number" step="any" name="Amt4" autocomplete="off" id="Amt4" class="amt" required><br><br>
JAVASCRIPT:
$('#Rate1').keyup(function(){
var Qty1;
var Rate1;
textone = parseFloat($('#Qty1').val());
texttwo = parseFloat($('#Rate1').val());
var result = textone * texttwo;
$('#Amt1').val(result.toFixed(2));
});
$('#Rate2').keyup(function(){
var Qty2;
var Rate2;
textone = parseFloat($('#Qty2').val());
texttwo = parseFloat($('#Rate2').val());
var result = textone * texttwo;
$('#Amt2').val(result.toFixed(2));
});
$('#Rate3').keyup(function(){
var Qty3;
var Rate3;
textone = parseFloat($('#Qty3').val());
texttwo = parseFloat($('#Rate3').val());
var result = textone * texttwo;
$('#Amt3').val(result.toFixed(2));
});
$('#Rate4').keyup(function(){
var Qty4;
var Rate4;
textone = parseFloat($('#Qty4').val());
texttwo = parseFloat($('#Rate4').val());
var result = textone * texttwo;
$('#Amt4').val(result.toFixed(2));
});
$('.rate').on('keyup', function() {
var result = 0;
var setResult = true;
$('.amt').each(function() {
if($(this).val() > 0) {
result += parseFloat(this.value);
}
});
$('#TotalInvoiceValue').val(result.toFixed(2));
});
I'm trying to calculate the values of multiple fields and place the total in another box. It works with whole numbers but for some reason won't add 7.25 or 7.50 for example.
I tried changing my tot += parseInt(arr[i].value).toFixed(2); but that didn't work. Any help is appreciated.
function findTotal(){
var arr = document.getElementsByName('monday');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('totalHours').value = tot;
}
Monday : <input onblur="findTotal()" type="text" name="monday" id="monday1"/><br>
Monday : <input onblur="findTotal()" type="text" name="monday" id="monday2"/><br>
Monday : <input onblur="findTotal()" type="text" name="monday" id="monday3"/><br>
Monday : <input onblur="findTotal()" type="text" name="monday" id="monday4"/><br>
Monday : <input onblur="findTotal()" type="text" name="monday" id="monday5"/><br>
Monday : <input onblur="findTotal()" type="text" name="monday" id="monday6"/><br>
<br><br>
Total : <input type="text" name="total" id="totalHours"/>
parseInt will remove the decimal part
you should use parseFloat
User parseFloat() instead of parseInt(),
function findTotal(){
var arr = document.getElementsByName('monday');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseFloat(arr[i].value))
tot += parseFloat(arr[i].value);
}
document.getElementById('totalHours').value = tot;
}
tot += Number(Number(arr[i].value).toFixed(2))
I have on page some elements with id`s with number of row in the end. For example
<input type="hidden" name="productid1" id="productid1" value="4941">
<input type="hidden" name="qty1" id="qty1" value="2">
<input type="hidden" name="productid2" id="productid2" value="4942">
<input type="hidden" name="qty2" id="qty2" value="1">
<input type="hidden" name="productid3" id="productid3" value="4941">
<input type="hidden" name="qty3" id="qty3" value="5">
i know elements count, and i`m need make js array with key from productidX value, and value sum of values qtyX
i tryed like that
var out = [];
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val())
}
but this is not working(
i`m need somesing like taht
[4931] => 7
[4942] => 1
can someone say me right way for this?
sorry for mistakes, english not my native language
Try to use a object {} like this example:
var out = {}; //change to a object
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
//now you can acess like properties/hashmap
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val());
}
You also need verify if is undefined before use += like this:
var out = {}; //change to a object
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
//now you can acess like properties/hashmap
if(out[jQuery('#productid'+i).val()])
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val());
else
out[jQuery('#productid'+i).val()] = parseFloat(jQuery('#devQty'+i).val());
}
You also have a little mistake using #devQty instead #qty and you need to parse the tot var:
var out = {}; //change to a object
var tot = parseInt(jQuery('#totitems').val());
for(var i = 1; i <= tot; i++)
{
if(out[jQuery('#productid'+i).val()])
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#qty'+i).val());
else
out[jQuery('#productid'+i).val()] = parseFloat(jQuery('#qty'+i).val());
}
console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--For testing-->
<input type="hidden" name="totitems" id="totitems" value="3">
<input type="hidden" name="productid1" id="productid1" value="4941">
<input type="hidden" name="qty1" id="qty1" value="2">
<input type="hidden" name="productid2" id="productid2" value="4942">
<input type="hidden" name="qty2" id="qty2" value="1">
<input type="hidden" name="productid3" id="productid3" value="4941">
<input type="hidden" name="qty3" id="qty3" value="5">
This is another way to do this:
var out = {};
jQuery("[name='product']").each(function(){
var value = parseFloat(jQuery(this).val());
var productID = jQuery(this).data("id");
if(out[productID])
out[productID] += value;
else
out[productID] = value;
});
console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="product" data-id="4941" value="2">
<input type="hidden" name="product" data-id="4942" value="1">
<input type="hidden" name="product" data-id="4941" value="5">
When I try to add several values, they just get appended.
These are my inputs (They all look the same):
<input type="number" id="floatOne" required>
This is my script:
<script>
function calcExactFloat(){
var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value,document.getElementById("floatFive").value,document.getElementById("floatSix").value,document.getElementById("floatSeven").value,document.getElementById("floatEight").value,document.getElementById("floatNine").value,document.getElementById("floatTen").value);
var sum = 0;
for(var i = 0; i < floats.length; ++i){
sum = sum + floats[i];
console.log(sum);
}
Values returned from inputs by .value are considered as string so you should to cast them to float then you can make calculation, so replace the following line :
sum = sum + floats[i];
By :
sum = sum + parseFloat(floats[i]);
Hope this helps.
var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value);
var sum = 0;
for(var i = 0; i < floats.length; ++i){
sum = sum + parseFloat(floats[i]);
}
result.textContent = sum;
<input type="number" id="floatOne" value='10'>
<input type="number" id="floatTwo" value='10'>
<input type="number" id="floatThree" value='10'>
<input type="number" id="floatFour" value='10'>
<br/>
Result : <span id="result"></span>
The value of input elements if a string, even if that string represent a numerical value. In JavaScript, an "addition" of strings results in concatenation - ('1' + '1') === '11'.
On order to convert the strings to numbers, the simplest way is to use a + before the variable - +a + +b.
Try like this:
var sum = 0;
for(var i = 0; i < floats.length; ++i){
sum = sum + +floats[i];
console.log(sum);
}
you have to use parseFloat
function calcExactFloat(){
var floats = new Array(document.getElementById("floatOne").value, document.getElementById("floatTwo").value,document.getElementById("floatThree").value,document.getElementById("floatFour").value,document.getElementById("floatFive").value,document.getElementById("floatSix").value,document.getElementById("floatSeven").value,document.getElementById("floatEight").value,document.getElementById("floatNine").value,document.getElementById("floatTen").value);
var sum = 0;
for(var i = 0; i < floats.length; i++){
if(floats[i])
sum = sum + parseFloat(floats[i]);
}
alert(sum)
}
<input type="number" id="floatOne" required><br />
<input type="number" id="floatTwo" required><br />
<input type="number" id="floatThree" required><br />
<input type="number" id="floatFour" required><br />
<input type="number" id="floatFive" required><br />
<input type="number" id="floatSix" required><br />
<input type="number" id="floatSeven" required><br />
<input type="number" id="floatEight" required><br />
<input type="number" id="floatNine" required><br />
<input type="number" id="floatTen" required><br />
<input type="button" value="Calc" onclick="calcExactFloat()" />
hy all ..
I have quetion about jquery keyup
1. how I can calculate total from quantity[] * price[]
2 how I can callculate grantotal from price[]
I have try like this but not working
Thanks
$('input[name="qty[]"').each(function(index, value){
$('input[name="qty[]"').on('keyup',function(){
var tot = $('input[name="price[]"').val() * this.value;
$('input[name="subT[]"').val(tot);
// console.log($('input[name="qty[]"'));
})
});
//});
$('input[name="qty[]').keyup(function () {
var sum = 0;
$('.subT').each(function() {
sum += Number($(this).val());
});
$('#grandtotal').val(sum);
});
Change this
$('input[name="price[]"]')
to
$('input[name="price[]"]').val()
So, it should look like this:
$('input[name="qty[]"]').keyup(function() {
$('input[name="prodid[]"]').each(function() {
var subT = parseFloat($(this).val()) * parseFloat($('input[name="price[]"]').val());
$('input[name="total[]"]').val($(this).val() * $('input[name="price[]"]').val());
});
});
Try
$('input[name="qty[]"]').keyup(function() {
var total = (this.value * $(this).next('[name="price[]"]').val()) || 0;
$(this).next().next('[name="total[]"]').val(total)
var grand = 0;
$('[name="total[]"]').each(function() {
grand += +this.value || 0;
});
$('[name="grand_total"]').val(grand)
}).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="prodid[]" type="hidden" value="116">
<input name="qty[]" type="text" value="1" maxlength="2" class="detailinformation--input qty">
<input name="price[]" type="hidden" value="5">
<input name="total[]" type="hidden" value="">
<input name="prodid[]" type="hidden" value="117">
<input name="qty[]" type="text" value="1" maxlength="2" class="detailinformation--input qty">
<input name="price[]" type="hidden" value="4">
<input name="total[]" type="hidden" value="">
<input name="grand_total" type="text" value="">