JAVASCRIPT: Getting values inside an array - javascript

I'm having a problem in calling the values I entered in the numberbox (I don't know what should I call it... if there's a textbox, there should be a numberbox. lol). If I enter "123456", the value of sum should be "21", but what happens is that the value of sum is "0123456".
<input type="number" name="user" id="input" maxlength="6" size="6" required>
<input type="button" onClick="Calculate()" value="Calculate">
<script type="text/javascript">
function Calculate(){
var user = [];
user=document.getElementById("input").value;
if(user.length==6){
var sum=0;
for (i=0;i<user.length;i++){
sum=sum+user[i];
}
var ave=sum/6;
window.alert("Sum is: "+sum);
window.alert("Average is: "+ave);
}
else
window.alert("Please input EXACTLY 6 numbers.");
}
</script>

You are retrieving a string breaking it into parts and adding it back together.You need to convert the string into an integer first. To find out the multiple ways to do this, a very good answer on that is written here:
How do I convert a string into an integer in JavaScript?
sum = sum + parseInt(user[i],10);
Should work

Related

Javascript parameters getting concatenated on trying to find sum [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
In this script i am passing number values but i get them as concatenated values.Why is javascript behaving so.I use a function named add and passing two number parameters.Why is it considered as string.I am using chrome browser
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>
<script>
const add=function( num1, num2){
return num1+num2;
}
</script>
You should avoid inline javascript and place javascript code in external js file. For better readability, debug and testing purposes.
From #Sascha answer you should convert input text to number and then do the calculations using parseInt. Also, check #Ajeet_Eppakayala answer as an alternative solution.
let submBtn = document.getElementById('sbtBtn');
function calculate(e){
e.preventDefault();
let num1El = document.getElementById('num1');
let num2El = document.getElementById('num2');
let res = document.getElementById('result');
let num1 = parseInt(num1El.value);
let num2 = parseInt(num2El.value);
if (Number.isInteger(num1) && Number.isInteger(num2)){
res.innerHTML = add(num1,num2);
}else{
res.innerHTML = "Please enter numbers";
num1El.focus();
}
}
const add = (num1,num2) => {
return parseInt(num1) + parseInt(num2);
}
submBtn.addEventListener('click',calculate);
<form>
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" id="sbtBtn" value="Sum" />
<p id="result"><p>
</form>
Because you get the values from an Input-field and this is allways from type string. So you had to use parseInt to get an Integer.
const add=function( num1, num2){
return parseInt(num1)+parseInt(num2);
}
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>
You need to parse values to int.
ShortHand for Int parsing is + operator or simple parseInt(<stringNumber>).
const add = function( num1, num2){
return +num1 + +num2;
}
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>

Validate two text fields together in html

I want to compare two text fields to make sure that the summation of two values should be equal to 100. I couldn't find any java script for this matter.
You din't explained your problem well, but I think this is what you want:
<input id="first" type="text">
<input id="second" type="text">
<button onClick="onClick()">Click me</button>
function onClick(){
var first = parseInt(document.getElementById("first").value);
var second = parseInt(document.getElementById("second").value);
var sum = first + second;
if (sum == 100)
{
...//Your code here...
}
}
Please tell me if this din't work for you.

Why this javascript and html code is not calculating the result?

This is the code:
<html>
<body>
<script>
function myFunction(var1,var2){
number=var1+var2
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo></p
</body>
</html>
When I insert 10 for number 1 and 20 for number 2, the output is:
1020
But i want it to display 30.
What can i do?
**I have tried myFunction(10,20), the result is 30.
simply use parse the variable value to integer using parseInt() method or add "+"before to your variable name. Because variables var1 and var2 returning string. To calculate those variable values, you need to convert it as a integer.
using parseInt() method
number=parseInt(var1)+parseInt(var2)
use + before variable name to convert into integer,
number= +var1 + +var2
try this code,
<html>
<body>
<script>
function myFunction(var1,var2){
number = parseInt(var1) + parseInt(var2)
//another way number= +var1+ +var2
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo"></p>
</body>
</html>
using parseInt() DEMO
using + before variable name DEMO
modify your function with parseInt like:
<script>
function myFunction(var1,var2){
number=parseInt(var1)+parseInt(var2);
document.write(number);
}
</script>
You were getting output like 1020 because by default data from the textbox is taken as text type, so we need to convert it to Number Type first, for that we are using parseInt(for explicit conversion)
Your javascript thinks you are appending strings... To make sure your javascript knows it's numbers your working with you need to convert it to that type.
<html>
<body>
<script>
function myFunction(var1, var2){
number = parseInt(var1, 10) + parseInt(var2, 10)
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo"></p>
</body>
</html>
For more info about parseInt check this documentation.
Update your method to
function myFunction(var1,var2){
number=parseInt(var1) + parseInt(var2)
document.write(number)
}
As this.form.no1.value is returning a string, so both the numbers are concatenated as strings instead of summing up as numbers.
Two options:
Change your input tag to
<input type="button" onclick="myFunction(parseInt(this.form.no1.value, 10),parseInt(this.form.no2.value, 10))" value="submit">
OR
Change your JavaScript function to
function myFunction(var1,var2){
var number=parseInt(var1, 10)+parseInt(var2, 10);
document.write(number);
}
It is because the values you extract from your input fields are strings. When you add two strings, they are usually concatenated. Try looking at the javascript method parseIntas Evan suggests in the comments or look at parseFloatif you want to allow floats.
parseFloat docs
Your method would then look like this:
function myFunction(var1,var2){
number = parseFloat(var1) + parseFloat(var2)
document.write(number)
}
It's now just string concatenation. Please use "parseInt()" to get the result.
thanks.
Your not doing a calculation, you are appending two Strings. In order to calculate the mathematical answer for var1 + var2 you should parse them to Integers.
result = parseInt(var1) + parseInt(var2);

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Reading numbers from inputs with JavaScript always returns NaN

I want to create a calculator which simply sums 2 fields up. But whatever I try it does not work. It also returns "NaN", also if I use parseInt().
Here's the code:
<script type="text/javascript" language="Javascript">
function doSum()
{
var a = document.getElementsByName("a").value;
var b = document.getElementsByName("b").value;
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
Sorry for that noob question, but what I'am doing wrong?
Thanks for any help!
Give ids to your inputs and identify them uniquely using document.getElementById. Then, obtain their decimal int values using parseInt with the radix parameter set to 10 and display the result as you currently do.
<script type="text/javascript" language="Javascript">
function doSum()
{
var a = parseInt(document.getElementById("a").value, 10);
var b = parseInt(document.getElementById("b").value, 10);
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input type="text" id="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" id="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
getElementsByName returns a list of elements and you'd have to refer to the one you want through an index, even if the list contains only one element.
getElementById on the other hand, returns an uniquely identified element, by its id.
use getElementById and give each of those an Id. getElementsByName returns an array. By the way.. it's not a bad question. It's a common error-- one that is addressed in a way by using jQuery which deals in wrapped sets.
getElementsByTagName returns a node list:
function doSum()
{
var a = document.getElementsByName("a")[0].value;
var b = document.getElementsByName("b")[0].value;
var sum = parseInt(a, 10) + parseInt(b, 10);
document.getElementById("sum").value = sum;
}
So you will need to index it. In addition in order not to do a string concate, parseInt with radix 10 is needed. Unless you plan to accept octal values in your calculator.
getElementsByName returns multiple elements, hence the plural Elements. You need to get the property of the first element found:
var a = document.getElementsByName('a')[0].value;
getElementsByName returns a NodeList: this is a set of all the elements found with that name. It is like an array in that you can use numeric indexes (like [0]) to access the elements found and in that there is a length property; no other array-like functionality is available.
Furthermore, the value property will always be a string if it is set. The + operator is the addition operator when the values are numbers; if they are strings, it is the concatenation operator. "1" + "2" is equal to "12" in Javascript. You need to use parseInt to convert them to numbers:
var a = document.getElementsByName('a')[0].value;
a = parseInt(a, 10); // parse as a number in base 10
Fields in JavaScript are all strings you need int, also .getElementsByName returns an array, you probably need the first element, so:
var a = parseInt(document.getElementsByName("a")[0].value, 10);
var b = parseInt(document.getElementsByName("b")[0].value, 10);
getElementsByName returns an array which gives you the wrong data type for what you are trying to do.
try:
function doSum()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input id="a" type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input id="b" type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
OK, two issues, your a fetching the valurs of a and b using getElementsByName which returns an array of values (since there could be many). Use getElementsById and put ids in the HTML.
Also the value properties will be strings so you will need to convert to numbers before doing your addition.
a and b are strings so :
function doSum()
{
var a = parseInt(document.getElementsByName("a").value);
var b = parseInt(document.getElementsByName("b").value);
var sum = a + b;
document.getElementById("sum").value = sum;
}

Categories