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))
Related
The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?
what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;
Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.
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">
I have form that adds 6 user inputs. I want to have an alert if the total is not 100 or the user enters something other than a number. The alert works for a total greater than 100, but how do you check if it's less than 100 and all the inputs have been filled in? Right now I get the alert when the first input is being filled in.
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" /><br>
<textarea type="text" name="total" id="total" min="100" max="100" readonly></textarea>
</form>
<script>
function findTotal(){
"use strict";
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
document.getElementById('total').value = tot;
if (tot > 100) {
alert("Please make sure numbers total 100");
document.getElementById("qty1").value = null;
document.getElementById("qty2").value = null;
document.getElementById("qty3").value = null;
document.getElementById("qty4").value = null;
document.getElementById("qty5").value = null;
document.getElementById("qty6").value = null;
document.getElementById("total").value = null;
return false;
}
if (tot < 100) {
alert("Please make sure numbers total 100");
document.getElementById("qty1").value = null;
document.getElementById("qty2").value = null;
document.getElementById("qty3").value = null;
document.getElementById("qty4").value = null;
document.getElementById("qty5").value = null;
document.getElementById("qty6").value = null;
document.getElementById("total").value = null;
return false;
}
}
</script>
To achieve expected result, use below option
1. Use onkeyup function to check whether input is number or not
2. Use if(tot >100) condition to check value greater than 100
3. if(tot <100) condition to check value less than 100 and alert placed on last field to avoid alert on every field
4.Clear values if conditions are met
HTML:
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" onkeyup="checkinput(this)" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" onkeyup="checkinput(this)" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" onkeyup="checkinput(this)" /><br>
<textarea type="text" name="total" id="total" min="100" max="100" readonly></textarea>
</form>
JS:
function findTotal() {
"use strict";
var arr = document.getElementsByName('qty');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
document.getElementById('total').value = tot;
if (tot > 100) {
alert("Please make sure numbers total 100");
for (i = 0; i < arr.length; i++) {
arr[i].value = null;
}
}
if (tot < 100 && arr[5].value) {
alert("Please make sure numbers total 100");
for (i = 0; i < arr.length; i++) {
arr[i].value = null;
}
}
}
function checkinput(x) {
var y = x.value
var regex = /^[0-9]+$/;
if (y.match(regex)) {} else {
alert("Enter number");
x.value = '';
}
}
Codepen- http://codepen.io/nagasai/pen/rLKkBb
Your code has been cliffed off, but just so you know this:
if (tot > 100) {
alert("Please make sure numbers total 100");
return false;
}
if (tot < 100) {
alert("Please make sure numbers total 100");
return false;
}
Is the same as writing this:
if(tot !== 100) {
alert("Please make sure numbers total 100");
return false;
}
Edit:
It's because your event is firing on the oninput event, which fires every time a user types. Use the on submit event which fires when the form is submitted. Make sure to prevent default actions. Comment if this doesn't help you.
One way you may be able to solve this is to exit out of the program if you can't parse all the inputs to ints. If the default value can be parsed to an int, then you may need to add a special case. Edit : Just replace the "return false" with whatever you want to happen when the user enters a non-integer value.
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
else{
return false;
}
}
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()" />
I need a basic loop to sum two fields. I just get it to work for one group, but the others remain the same. I know I need some kind of array to solve this, but I can't work it out. (Notice, they are 50 groups in the original project, but I just added 2) Here is the code:
HTML
<label>Value 1:</label><input type="text" name="value1[]" id="txtval1"><br>
<label>Value 2:</label><input type="text" name="value2[]" id="txtval2"><br>
<label>Total:</label><input type="text" name="total[]" id="txttotal"><br><br>
<label>Value 1:</label><input type="text" name="value1[]" id="txtval1"><br>
<label>Value 2:</label><input type="text" name="value2[]" id="txtval2"><br>
<label>Total:</label><input type="text" name="total[]" id="txttotal">
<br><br>
<button type="button" onclick="myFunction(); return false;">Get Total</button>
Javascript
<script type="text/javascript">
function myFunction()
{
var val1 = document.getElementById('txtval1').value;
var val2 = document.getElementById('txtval2').value;
var total = document.getElementById('txttotal');
var sum = parseInt(val1) + parseInt(val2);
if (val1.value!='' && val2.value!=''){
total.value='';
total.value = total.value + sum;
}
}
</script>
I don't know why this doen't work on my fiddle, but does in my local machine. Here is the Fiddle
I think that giving the same ID to two elements It is mistake.
You have to give a different ID for each element and pass them on for.
Look at this fiddle:
http://jsfiddle.net/83m6e/
EDIT: I changed the fiddle for option2:
http://jsfiddle.net/83m6e/3/
You also can put each segment into a div and then do not change the names.
You can not add up to arrays in order to add up their elements. You must do it one by one. Try this code:
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var count = 3;
var val1, val2, sum;
for (var i = 0; i < count; i++)
{
val1 = document.getElementById('txtval1_' + i).value;
val2 = document.getElementById('txtval2_' + i).value;
sum = parseInt(val1) + parseInt(val2);
document.getElementById('txttotal_' + i).value = sum;
}
}
</script>
</head>
<body>
<label>Value 1:</label><input type="text" id="txtval1_0"><br>
<label>Value 2:</label><input type="text" id="txtval2_0"><br>
<label>Total:</label><input type="text" id="txttotal_0"><br><br>
<label>Value 1:</label><input type="text" id="txtval1_1"><br>
<label>Value 2:</label><input type="text" id="txtval2_1"><br>
<label>Total:</label><input type="text" id="txttotal_1"><br><br>
<label>Value 1:</label><input type="text" id="txtval1_2"><br>
<label>Value 2:</label><input type="text" id="txtval2_2"><br>
<label>Total:</label><input type="text" id="txttotal_2"><br><br>
<button type="button" onclick="myFunction(); return false;">Get Total</button>
</body>
</html>