Adding values coming from input in js - javascript

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()" />

Related

Adding numbers across multiple fields wont add decimals

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))

Calculate the values of input where each input has different prices. Any shorter code for this?(javascript only)

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.

How To Get Total Value Of Inputs With Vanilla Javascript?

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">

validating the sum of inputs in text area

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;
}
}

Get value from element id instead of name in javascript

I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:
<script type="text/javascript">
//auto commas
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
//sub total
function checkTotal() {
document.cc_form.total.value = '';
var sum = <?=$days*$_rate*$_rooms?>;
for (i=0;i<document.cc_form.cost.length;i++) {
if (document.cc_form.cost[i].checked) {
sum = sum + parseInt(document.cc_form.cost[i].value);
}
}document.cc_form.total.value = doThousands(sum);
}
</script>
And this is the HTML:
<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />
</form>
document.getElementById http://www.w3schools.com/jsref/met_doc_getelementbyid.asp

Categories