How i can add value as number - javascript

i have problem because it code don't calculate value.
I wrote 11 and is Expenditure: 11, next i wrote 11 and is 1111, but i need 22 so i used minusValue.value += a;
Do you know where is error?
var minusCashField = document.getElementById('minusCashField');
minusCash.addEventListener("click", function() {
var a = minusCashField.value;
minusValue.value += a;
});
<div class="threeBox">
<div class="resultbutton">
<input class="minusValue" disabled id="minusValue" value=''>
</div>
</div>
</header>
<div class="addFunction">
<fieldset>
<label><strong>Expenditure:</strong></br></label>
<input placeholder="Enter Expenditure...." tabindex="2" required type="text" id="minusCashField">
<button type="submit" id="minusCash">Submit</button>
</fieldset>
</div>

input.value is returning a string, not a number.
You could convert the string to a number by using a unary plus +.
var number = +input.value;
// ^

your concatinating 2 strings you need to convert them to integers.
var minusCashField = document.getElementById('minusCashField');
minusCash.addEventListener("click", function() {
var a = parseInt(minusCashField.value || 0, 10);
minusValue.value = parseInt(minusValue.value || 0, 10) + a;
});

Because the values of those inputs will be strings, you need to convert the strings to numbers before any math operations can be performed - both the string value you assign to a, and the value contained in the results to which you add a.
minusCash.addEventListener("click", function() {
var a = Number(minusCashField.value);
minusValue.value = Number(minusValue.value) + a;
});

use parseInt() to convert the string to integer.
var minusCashField = document.getElementById('minusCashField');
minusCash.addEventListener("click", function() {
var a = parseInt(minusCashField.value || 0, 10);
minusValue.value = parseInt(minusValue.value || 0, 10) + a;
});
<div class="threeBox">
<div class="resultbutton">
<input class="minusValue" disabled id="minusValue" value=''>
</div>
</div>
</header>
<div class="addFunction">
<fieldset>
<label><strong>Expenditure:</strong></br></label>
<input placeholder="Enter Expenditure...." tabindex="2" required type="text" id="minusCashField">
<button type="submit" id="minusCash">Submit</button>
</fieldset>
</div>

Related

adding the sum of two separate functions

(ETA: I'm working on this for a class and the teacher wants everything to be "oninput"...yes, it's annoying :p )
I'm working on a form where each function miltiplies a number and gives me a "subtotal" on input. I'd like to take the two "subtotal" answers from the two functions and add them togething into a "total" amount. I feel like this should be simple but nothing I've tried works.
Here's what I've got in the javascript that works to give me the two subtotals:
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
document.getElementById('subTotalOne').innerHTML = '$ ' + qty1 * 19.99;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
document.getElementById('subTotalTwo').innerHTML = '$ ' + qty2 * 37.99;
}
Here's the important parts of the html:
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()"/><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()"/><br>
</div>
<div class="price">
<label for="price">Price</label>
<p>$19.99</p>
<p>$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
I'm trying to add the subTotalOne and subTotalTwo and have them output at orderTotal, essentially. :)
Thanks!
//Global variables (concidering ID is unique)
let subTotalOne, subTotalTwo, qty1, qty2, orderTotal;
const setup = () => {
subTotalOne = document.getElementById('subTotalOne');
subTotalTwo = document.getElementById('subTotalTwo');
qty1 = document.getElementById('qty1');
qty2 = document.getElementById('qty2');
orderTotal = document.getElementById('orderTotal');
myCalculator();
myCalculatorTwo();
};
const updateTotal = (target, value) => {
if(target == null || value == null || Number.isNaN(value)) return;
target.textContent = `$ ${value.toFixed(2)}`;
target.setAttribute('data-value', value.toFixed(2));
}
const getTotal = () => {
if(subTotalOne == null || subTotalTwo == null) return 0;
const [value1, value2] = [
Number.parseFloat((subTotalOne.dataset?.value ?? 0), 10),
Number.parseFloat((subTotalTwo.dataset?.value ?? 0), 10)
];
if(Number.isNaN(value1) || Number.isNaN(value2)) return;
else return value1 + value2;
};
const updateOrderTotal = () => updateTotal(orderTotal, getTotal());
const myCalculator = () => {
const value = Number.parseFloat(qty1.value || 0, 10) * 19.99;
updateTotal(subTotalOne, value);
updateOrderTotal();
}
const myCalculatorTwo = () => {
const value = Number.parseFloat(qty2.value || 0, 10) * 37.99;
updateTotal(subTotalTwo, value);
updateOrderTotal();
}
window.addEventListener('load', setup);
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()" min="0"><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()" min="0"><br>
</div>
<div class="price">
<label for="price">Price</label>
<p data-value="19.99">$19.99</p>
<p data-value="37.99">$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
Here's how you do it:
function orderTotal() {
const qty1 = document.getElementById('qty1').value;
const qty2 = document.getElementById('qty2').value;
const total = parseInt(qty1) + parseInt(qty2);
document.getElementById('orderTotal').innerHTML = '$ ' + total;
}
Remove the oninput="orderTotal()" in your span element and trigger the above function using a button click e.g. <button onClick="orderTotal()">Calculate Total</button> or maybe when either of your two inputs' value changes. Also consider using const and let instead of var.
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
Instead of querying the DOM in Ray's answer--as DOM queries should generally be avoided since they are slow W3 Wiki, you could also consider using a shared variable between the two functions.
Also, consider using something else in place of innerHTML, mostly because of efficiency why-is-element-innerhtml-bad-code.
var total1;
var total2;
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
total1 = qty1 * 19.99
document.getElementById('subTotalOne').textContent = '$ ' + total1;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
total2 = qty2 * 37.99;
document.getElementById('subTotalTwo').textContent = '$ ' + total2;
}
function orderTotal() {
document.getElementById('orderTotal').innerHTML = '$ ' + (total1 + total2);
//parentheses because '$' isn't a number so the numbers total1 and total2 will be treated like strings and joined together
}

Javascript input returns NaN or undefiend

I'm making a tip calculator and I would like the tip amount to display for the user to see. The problem I'm having is the output showing up as 'NaN' or 'undefined'. I've tried making changes to my code but I keep getting the same result.
function calculateTip() {
var billInput = document.getElementById('bill');
var tipPercentage = document.getElementById('tip');
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', +tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You forgot to get the value of your fields. Because without the property .value, it returns HTMLObject.
function calculateTip() {
var billInput = parseFloat(document.getElementById('bill').value);
var tipPercentage = parseFloat(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', + tipAmount;
};
You are reading billInput and tipPercentage as HTML element objects instead of the text the user types into them, which will be their .value properties.
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You're loading the element instead of the element value when declaring the variables billInput and tipPercentage. Try with this code:
var billInput = document.getElementById('bill').value;
var tipPercentage = document.getElementById('tip').value;

If the input I put blank, then it will count 0

I am trying to put some amount, then it will show the calculation if all input will given any number, but I want, when I do not put anything in any one of that input, then the input will count "0" automatically..
<body>
<input type='text' id='aaa'/>
<input type='text' id='bbb'/>
<input type='text' id='ccc'/>
<input type='text' id='answer' name='ans' />
<form name ="testarea" Method="GET" Action="" id='form1'>
<input type="button" onClick="Calculate();" value="calculate"/>
</form>
</body>
<script>
function Calculate()
{
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = parseFloat(aaa) * 82;
var permin1 = parseFloat(bbb) * 40;
var permin2 = parseFloat(ccc) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
document.form1.submit();
}
</script>
var aaa= document.getElementById('aaa').value;
var bbb= document.getElementById('bbb').value;
var ccc= document.getElementById('ccc').value;
var permin = (parseFloat(aaa)||0) * 82;
var permin1 = (parseFloat(bbb)||0) * 40;
var permin2 = (parseFloat(ccc)||0) * 10;
var permin3=permin+permin1+permin2;
document.getElementById('answer').value=permin3;
You can use the OR operator to replace NaN with 0 if parseFloat returns NaN.
You could shorten the upper code to:
const ids = ["aaa","bbb","ccc"];
const factors = [82,40,10];
document.getElementById("answer").value = ids.reduce((count,id,index) => {
const { value } = document.getElementById(id);
return count + (parseFloat(value) || 0) * factors[index];
}, 0);
An alternative you can do is use a default parameter for your function.
Your calculate would look something like this:
Calculate(aaa=0, bbb, ccc) {
And this question covers how to pass html elements as parameters for functions.
Instead of using an if/else construct you can rely on the falsy value of an empty string.
Therefore you can initialize all your variables like this:
var aaa = document.getElementById('aaa').value || '0';
More information on falsy values can be found on the MDN.

Why it gives me String every time?

I got input from input tags but whatever I write in inputs it recognize as string value so that I can't use my conditions.
and the second problem if I enter "ddd" for first input and "111" for second input and press button it shows NaN in console. I want to show alert instead of this. How can I correct these?
function addFunc() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
if (typeof x == 'string' || typeof y == 'string') {
var result = parseInt(x) + parseInt(y);
console.log(result);
} else {
alert("Wrong Entry!");
}
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
The value of an input field will always be a string. Try using isNaN() to determine if the decimal parsed correctly:
function addFunc() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>
Alternatively, if you want to eliminate all bad input (1e would be invalid), try using a + symbol before the string value to convert it to a number. If the string can't be converted, it will return NaN:
function addFunc() {
var x = +document.getElementById("num1").value;
var y = +document.getElementById("num2").value;
if ( !isNaN(x) && !isNaN(y) )
{
var result = x + y;
console.log(result);
}
else {
alert("Wrong Entry!");
}
}
<form onsubmit="addFunc(); return false">
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" value="Add" />
</form>

Auto calculation occurs on previous value

i have a function that increments a number, takes the total and multiplies it by a price. However, when I click the button that increments for the first time it doesn't do anything. I click the button a second time and it works. However if I then click the button that decreases, then it does the previous function (e.g. adding) then pressing it a second time will decrease the value.
I understand that the onClick="myFunction()" may be in the wrong place, however I don't know where to put it. I want the total to be calculated automatically. A demo can be found at http://alpha.kentishtours.co.uk/destinations/bruges.php
The function that takes the value and multiplies it and calculates the total.
function myFunction()
{
var a = document.getElementById('adult').value;
z=39;
x=a*z;
var c = document.getElementById('child').value;
if(a >= 1) {
a=+30; }
else {
a=+39; }
b=c;
c=a*b
d=x+c
document.getElementById("total").innerHTML=d;
document.getElementById("value").value = d;
}`
These are the buttons that increment the number and call the function to calculate.
<div class="calculator">
<div class="calculator-submodule input-group">
<h4>Adult (12+)</h4>
<button class="btn theme-btn" id="decrease" value="Decrease Value" onClick="myFunction()" >-</button>
<input type="text" id="adult" value="1" class="form-control input-usmall" min="0" disabled>
<button class="btn theme-btn" id="increase" value="Increase Value" onClick="myFunction()" >+</button>
</div>
<div class="calculator-submodule input-group">
<h4>Child (2-11)</h4>
<button class="btn theme-btn" id="decreasec" value="Decrease Value" onClick="myFunction()" >-</button>
<input type="text" id="child" value="0" class="form-control input-usmall" min="0" disabled>
<button class="btn theme-btn" id="increasec" value="Increase Value" onClick="myFunction()" >+</button>
</div>
<div class="calculator-submodule">
<span class="pound">£</span>
<span id="total">39</span><span class="pound">.00</span>
</div>
You have functions in your increment.js script that change the value of the input after you get them in "myfuntion". You need to calculate the prices after the values are changed.
So first you should remove the lines below from this file:
http://alpha.kentishtours.co.uk/assets/scripts/increment.js
$("#increase").click(function(){
var $n = $("#adult");
$n.val(Number($n.val())+1);
});
$("#decrease").click(function(){
var $n = $("#adult");
$n.val(Number($n.val())-1);
});
$("#increasec").click(function(){
var $n = $("#child");
$n.val(Number($n.val())+1);
});
$("#decreasec").click(function(){
var $n = $("#child");
$n.val(Number($n.val())-1);
});
Also remove the onClick="myFunction()" attribute in your HTML form.
Then change all your myFunction script to this:
var adult = $('#adult'),
child = $('#child'),
total = $('#total'),
value = $('#value'),
increase = $('#increase'),
decrease = $('#decrease'),
increasec = $('#increasec'),
decreasec = $('#decreasec');
var calulate_price = function(a, c){
var p1 = 39,
p2 = 30,
PA = a * p1,
PC, d;
if(a >= 1) PC = c * p2;
else PC = c * p1;
d = PA + PC;
total.text(d);
value.val(d);
};
increase.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
adult.val(++a);
calulate_price(a, c);
});
decrease.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
adult.val(--a);
calulate_price(a, c);
});
increasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
child.val(++c);
calulate_price(a, c);
});
decreasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());
child.val(--c);
calulate_price(a, c);
});
Everything working: http://jsbin.com/ohUniCa/2/edit?js,output

Categories

Resources