Input fields:
<input name="qty1" id ="qty1" type="text" onblur="sum()"/>
<input name="qty2" id ="qty2" type="text" onblur="sum()"/>
<input name="qty3" id ="qty3" type="text" onblur="sum()"/>
<input name="qty4" id ="qty4" type="text" onblur="sum()"/>
<input name="total" id ="total" type="text"/>
Javascript:
<script type="text/javascript">
function sum(){
//grab the values
qty1 = document.getElementById('qty1').value;
qty2 = document.getElementById('qty2').value;
qty3 = document.getElementById('qty3').value;
qty4 = document.getElementById('qty4').value;
document.getElementById('total').value = parseFloat(qty1) + parseFloat(qty2) + parseFloat(qty3) + parseFloat(qty4);
}
</script>
Code displays 4 fields where user can insert a number, the 5th field recalculates the total e.g.: 1st field (qty1): 1, 2nd field (qty2): 2, 3rd field (qty3): 3, 4th field (qty4): 4, 5th field (total): 10 (1+2+3+4 = 10).
I would like to make this code more user friendly, so the script automatically treats empty fields as 0. Currenly if user leave field empty, the total shows "NaN"
Any advise?
Thanks,
Tom
use isNaN function to determine the value if value exist and is numeric or not and assign default value if it does not.
if(!isNan(qty4)){
qty=0;
}
Ironically, if you didn't use parseFloat, then you wouldn't get NaN in the first place. parseFloat('') returns NaN.
You should still convert the strings to numbers though, but instead of parseFloat, use the unary + operator. +'' returns 0, because the mathematical value of an empty string is 0:
function sum(){
//grab the values
var qty1 = +document.getElementById('qty1').value;
var qty2 = +document.getElementById('qty2').value;
var qty3 = +document.getElementById('qty3').value;
var qty4 = +document.getElementById('qty4').value;
document.getElementById('total').value = qty1 + qty2 + qty3 + qty4;
}
Now you only get NaN if the the user provides a value that cannot be converted to a number, such as abc. To fix that, you can indeed use isNaN.
Here is fixed and more concise version of your code, making use of reduce:
function sum(){
document.getElementById('total').value =
[1, 2, 3, 4].reduce(function(total, id) {
var v = +document.getElementById('qty'+id).value;
return total + isNan(v) ? 0 : v;
}, 0);
}
function sum(){
//grab the values
qty1 = document.getElementById('qty1').value || 0;
qty2 = document.getElementById('qty2').value || 0;
qty3 = document.getElementById('qty3').value || 0;
qty4 = document.getElementById('qty4').value || 0;
document.getElementById('total').value = parseFloat(qty1) + parseFloat(qty2) + parseFloat(qty3) + parseFloat(qty4);
}
Related
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
I have 3 input fields:
<input type="text" id ="v0" onkeyup="calculate()"><br>
<input type="text" id ="v1" onkeyup="calculate()"><br>
<input type="text" id="result" onkeyup="calculate()" readonly><br>
What I am trying to do is to count number from 1st input divided by number from 2nd input and displaying it in 3rd input.
function calculate(){
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" && document.getElementById('v1').value ==""){
result.value ="";
}
}
Code is working fine for ADDING this input values, but I need to DIVIDE values from input fields.
I tried to replace "+" with "/" but it breaks the functionality.
You could try a simpler approach like this:
function calculate () {
var input1 = document.querySelector('#v0').value;
var input2 = document.querySelector('#v1').value;
if (input1 && input2) {
document.querySelector('#result').value = (input1 / input2).toFixed(2);
}
}
First of all you have to use "-" for subtraction. But if you want to perform division the problem is that during the first iteration you have total as 0, and it would be:
iteration[1]: 0/anything = 0
iteration[2]: 0/anything = 0
and so on
So you if you want to perform division you need initial value for total, it has to be the 1st input.
Hope that helps.
I have an array of 6 values where 6th value is optional (i.e. if user does not input 6th value, the first 5 values will be calculated). I want to sum highest 5 values of them.
My Javascript Code:
function calculate_merit_point(){
var s1 = eval(document.getElementById('sub_no1').value);
var s2 = eval(document.getElementById('sub_no2').value);
var s3 = eval(document.getElementById('sub_no3').value);
var s4 = eval(document.getElementById('sub_no4').value);
var s5 = eval(document.getElementById('sub_no5').value);
var s6 = eval(document.getElementById('sub_no6').value);
var vals = [s1,s2,s3,s4,s5,s6];
function arraySum(arr) {
if (!arr) {
return false;
} else {
var sum = 0;
for (var i = 0, len = arr.length; i < len; i++) {
sum += arr[i];
}
return sum;
}
}
sum = arraySum(vals.sort(function(a, b) {
return b - a;
}).slice(0, 5));
if(isNaN(tt)){
$('#agr').text('0');
} else {
$('#agr').text(sum);
}
}
Now suppose
s1 = 30
s2 = 31
s3 = 32
s4 = 33
s5 = 34
s6 = 35
It should be 31+32+33+34+35 = 165. but it is displaying the value 162.
As per my requirement (6th value optional), if I do not give any value to s6, it is displaying the value 228.
I have tried This, but if I do not give the 6th (optional) value, it is showing the value 0. If I give the value 35 in s6, it is showing sum value 233.
What should I do ?
UPDATE & RESOLVED
My code was correct. But something was creating problem with the code eval(). I replaced it with Number() and it was resolved.
Thank you all.
This would be a great opportunity to use .reduce. Which will return a single value given an array. While we're "looping" through the array, we will determine the lowest value, and then subtract that from the result. Also, you're clearly using jQuery to apply the .text() so, may as well use it to get the .val() of each of your inputs. Then we'll use parseInt with a check to return 0 in the event of an error/invalid result
JSFIDDLE
HTML
<input id="sub_no1" value="30" />
<input id="sub_no2" value="31" />
<input id="sub_no3" value="32" />
<input id="sub_no4" value="33" />
<input id="sub_no5" value="34" />
<input id="sub_no6" value="35" />
<p id="agr"></p>
JS
$(function() {
function calculate_merit_point() {
var s1 = getValue($('#sub_no1'));
var s2 = getValue($('#sub_no2'));
var s3 = getValue($('#sub_no3'));
var s4 = getValue($('#sub_no4'));
var s5 = getValue($('#sub_no5'));
var s6 = getValue($('#sub_no6'));
var vals = [s1, s2, s3, s4, s5, s6];
function getValue(el) {
return parseInt(el.val(), 10) || 0;
}
function arraySum(arr) {
if (!arr) {
return 0;
} else {
var lowest = Infinity;
return vals.reduce(function(sum, val) {
if (val < lowest){ lowest = val; }
return sum + val;
}, 0) - lowest;
}
}
$('#agr').text(arraySum(vals));
}
calculate_merit_point();
})
You can sum more easily with reduce, and subtract the highest value with Math.max using this ES6 code:
var vals = [30,31,32,33,34,35,36];
// Get sum
var sum = vals.reduce( (a,b) => a+b, 0 );
// Subtract highest value
if (vals.length == 6) sum -= Math.max(...vals);
// Output result
console.log(sum);
Here is that code integrated with the element names you mention in your code, but using jQuery also for the first part:
function calculate_merit_point(){
// Get all six input elements by using jQuery with a smarter selector:
var vals = $('[id^=sub_no]').map(function () {
return parseInt($(this).val()); // get the value as numeric for each of them
}).get().filter(n => !isNaN(n)); // filter the result to get real numbers only
// get sum
var sum = vals.reduce( (a,b) => a+b, 0 );
// Remove greatest value from it if we have 6 numbers
if (vals.length == 6) sum -= Math.max(...vals);
// Output the result.
$('#agr').text(sum);
}
calculate_merit_point();
$('input').on('input', calculate_merit_point);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sub_no1" value="1"><br>
<input id="sub_no2" value="2"><br>
<input id="sub_no3" value="3"><br>
<input id="sub_no4" value="4"><br>
<input id="sub_no5" value="5"><br>
<input id="sub_no6" value="6"><br>
<hr>
Sum: <span id="agr"></span>
You can adjust the values when running the above snippet and the sum will adapt.
ES5 equivalent
For when you don't have ES6 support:
function calculate_merit_point(){
// Get all six input elements by using jQuery with a smarter selector:
var vals = $('[id^=sub_no]').map(function () {
return parseInt($(this).val()); // get the value as numeric for each of them
}).get().filter(function (n) {
return !isNaN(n); // filter the result to get real numbers only
});
// get sum
var sum = vals.reduce(function (a,b) {
return a+b;
}, 0);
// Remove greatest value from it if we have 6 numbers
if (vals.length == 6) sum -= Math.max.apply(Math, vals);
// Output the result.
$('#agr').text(sum);
}
calculate_merit_point();
$('input').on('input', calculate_merit_point);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sub_no1" value="1"><br>
<input id="sub_no2" value="2"><br>
<input id="sub_no3" value="3"><br>
<input id="sub_no4" value="4"><br>
<input id="sub_no5" value="5"><br>
<input id="sub_no6" value="6"><br>
<hr>
Sum: <span id="agr"></span>
I'd prefer to not use regex, but if needed, so be it.
I have some code and I want to take a user's input and check to make sure that it is an isbn 10. In other words it must be a 10 digit number or a 9 digit number with an x at the end (the x represents the number 10). For my purposes, I'd like to turn the users input into an array of each digit. If there is an x I'd like to change that into a 10. I am having trouble doing this! I have seen other questions that are somewhat similar and they all use regex. Like I said, I'd prefer to not use regex, but if need be...
<h1>Problem #3:</h1>
<form name= "form">
<input id= "input" name= "isbn" type="number" placeholder="Enter your ISBN-10" min="0" />
<input id= "button" type="button" name="Validate" value="Validate" />
</form>
<div id="validISBN">
Valid ISBN
</div>
<div id="invalidISBN">
Invalid ISBN
</div>
<script src="js/jquery-2.0.3.min.js"></script>
<script>
$( document ).ready(function() {
alert("Welcome to ISBN Validator!");
//Add the event listener for the validate button here
//Look at toggling the CSS display property based on the result
$("#button").click(function(){
checker(document.form.isbn.value);
});
});
var checker = function(isbn){
isbn = isbn.toString().split('');
if (isbn[9] == 'x'|| isbn[9] == 'X') {
isbn[9] = 10;
}
if (isbn.length !== 10) {
alert("invalid ISBN!" + isbn.length);
}
else{
var sum = 0;
for (var x=10; x>0; x--){
sum += x*isbn[10-x];
}
alert("FINAL!!" + sum%11);
}
}
Input: 0375726721
Output: FINAL!!0
:Works
Input:067978330X
Expected Output: FINAL!!0
Actual Output: Invalid ISBN!0
:Does not work!
var isbn = '074759582x';
if (!/^\d{9}(\d|x)$/i.test(isbn)) // validation with regexp
alert('Invalid ISBN');
else {
var arr = isbn.split('');
arr[9] = arr[9].toLowerCase() == 'x' ? 10 : arr[9]; // replacement of x by 10
// below is your summation, just performed in another way.
var total = arr.map(function(el, index, arr) {
return (index + 1) * arr[10 - index - 1];
}).reduce(function(a, b) {return a + b;});
alert(total % 11);
}
Done
var isbn = '074759582x';
Split the string into characters using split. Apply map to grab the x and convert it to 10 if necessary. Then map each character to a number
array = isbn
.split('')
.map(function(char, i) {
return i === 9 && char.toLowerCase() === 'x' ? 10 : char;
})
.map(Number)
;
The ISBN is valid if it's of length 10, and there are no NaNs in it.
valid = array.length === 10 && !array.some(isNaN);
Checksum uses reduce, as in another answer:
sum = array.reduce(function(result, v, i) {
return result + (10-i) * v;
}, 0) % 11;
Problem #3:
<form name= "form">
<input id= "input" name= "isbn" type="number" placeholder="Enter your ISBN-10" min="0" />
<input id= "button" type="button" name="Validate" value="Validate" onclick = "checker()" />
</form>
<div id="validISBN">
Valid ISBN
</div>
<div id="invalidISBN">
Invalid ISBN
</div>
<script>
function checker () {
isbn = document.form.isbn.value;
isbn = isbn.toString().split('');
if (isbn[9] == 'x' || isbn[9] == 'X') {
isbn[9] = 10;
}
if (isbn.length !== 10) {
alert("invalid ISBN!" + isbn.length);
}
else {
var sum = 0;
for (var x = 10; x > 0; x--) {
sum += x * isbn[10 - x];
}
alert("FINAL!!" + sum % 11);
}
}
</script>
Hi I'm making a calculation in which I add up the values of all text inputs and get a total that I set as the value of another text input. I think this code should work for that, but it returns NaN. What am I doing wrong?
var sum = 0;
$('.price').each(function() {
amt = parseFloat($(this).val());
sum += Number(amt);
});
console.log(sum);
$("#order-total").val("€" + sum);
Use zero if the value is not a number, and remove anything that could cause an error
var sum = 0;
$('.price').each(function() {
amt = parseFloat($(this).val().replace(/[^0-9,.]/g, '').replace(',','.')) || 0;
sum += amt;
});
$("#order-total").val("€" + sum);
well you have written &euro in the value field I guess it is creating problem
<td><input type="text" class="price" value="€0"></td>
put this instead of above code
<td><input type="text" class="price" value="0"></td>
put below code to put validation
sum += isNaN(amt) ? 0 : amt;
Remove € sign before convert it to float and check that result is a number before to sum it:
var sum = 0;
$('.price').each(function() {
// val() will return something like "€45.6";
amt = parseFloat($(this).val().substring(1)));
sum += isNaN(amt) ? 0 : amt;
});
console.log(sum);
$("#order-total").val("€" + sum);
You just need to check the 1st character to see if its a euro symbol and if so, remove it.
You need to look for the character not the entity:
$('.price').each(function() {
var value = $(this).val();
if (value.charAt(0) === '\u20AC')
value = value.substr(1);
sum += parseFloat(value);
});