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>
Related
Can anyone please help me with the code. im trying to generate numbers from range 12012300 to 12012400 in sequence and without repetition. Will be great if message is displayed saying generated number is reserved, below the textbox.
Thanks heaps in advance
<form>
<input name="code" id="code" type="text" placeholder="#########" value="" readonly />
<script type="text/javascript">
function makeid() {
return Math.floor(Math.random() * 100) + 12012300;
}
</script>
<input type="button" value="Generate Code" onclick="document.getElementById('code').value = makeid()"></input>
<input type="reset" value="Reset" />
</form>
You can use the basic example of closure, self-invoking function
If you need sequential numbers you do not need to use Math.random
let makeid = (() => {
let id = 12012300;
return () => {
if(id > 12012400 ) throw( 'max id reached')
return id++;
};
})();
console.log(makeid())
console.log(makeid())
console.log(makeid())
This question already has answers here:
copy and concatenate values of multiple input boxes in a form to one input field
(2 answers)
Closed 5 years ago.
I want to concatenate the textInputs on clicking the button.
e.g text1=2 , text2=3 , text3=9 and text4=8, the final result should be 2398.
How to achieve this?
If you were using ES6 standards, you can use string literals
const txt1 = 'rt';
const txt2 = 'rete';
const concatenated = `${txt1}${txt2}`
you can refer the link for further learning:
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/template_strings
create one onChangeHandler() for textInput such as:
<TextInput onChange={(text)=>(this.onChangeHandler("text1",text))}>
<TextInput onChange={(text)=>(this.onChangeHandler("text2",text))}>
<TextInput onChange={(text)=>(this.onChangeHandler("text3",text))}>
onChangeHandler=(name,value)=>{
this.setState({[name]:value})
}
then on button click do this:
onButtonClick=()=>{
let finalText =this.state.text1+this.state.text2+this.state.text3
console.log(finalText) //prints the concatenated text.
}
With Pure JS
function concatenate(){
var concatenate = document.getElementById("input1").value + document.getElementById("input2").value + document.getElementById("input3").value
document.getElementById("result").innerHTML = "Resultat:"+concatenate
}
<input id="input1" type="text" name="name1" >
<input id="input2" type="text" name="name2" >
<input id="input3" type="text" name="name3" >
<button type="button" onclick="concatenate()">concatenate</button>
<div id="result">Resultat: </div>
This question already has answers here:
Addition operation issues?
(5 answers)
Closed 5 years ago.
I am new to java script, I have three text fields with ids text1, text2, text3 respectively. I want to input values in 2 of them and print the sum in the third.
my code looks like this please tell me, what am I doing wrong.
it is adding them as string not numbers.
Also I want to make it like, if I enter value in any 2 of the three boxes. The other one adjusts itself.
EX: '__' + 5 = 7 => ' 2 ' + 5 = 7
will it work if I put variables in value attribute. if So then How?
<html>
<head>
<script>
function myCalculator(a, b) {
c = a + b;
document.getElementById("text3").value = c;
}
</script>
</head>
<body>
<p>
<h1>Calculator</h1>
<input type="text" value="" id="text1"></input> + <input type="text" value="" id="text2"></input> = <input type="text" value="" id="text3"></input>
<input type="button" value="ADD" onclick='myCalculator(document.getElementById("text1").value,document.getElementById("text2").value)'></input>
</p>
</body>
</html>
Use the Number() to convert the strings to numbers. Anything inside a text input.value will initially be a string.
function myCalculator(a, b) {
var c = Number(a) + Number(b);
document.getElementById("text3").value = c;
}
You need to call parseInt(text) on both parameters of myCalculator function to convert them to numbers first.
function myCalculator(a,b){
a = parseInt(a, 10); // convert to integer first
b = parseInt(b, 10);
c=a+b;
document.getElementById("text3").value = c;
}
The second parameter of parseInt function is radix, which needs to be 10 to read numbers in decimal system. It is 10 by default from ES5.
Replace Your Code this with text block , First remember to pass id in quotes and second format your value from string to javascript before adding.
<html>
<head>
<script>
function myCalculator(a,b){
var c=parseInt(a)+parseInt(b);
document.getElementById('text3').value = c;
}
</script>
</head>
<body>
<p>
<h1>Calculator</h1>
<input type="text" value="" id="text1"></input> + <input type="text" value="" id="text2"></input> = <input type="text" value="" id="text3"></input>
<input type="button" value="ADD" onclick='myCalculator(document.getElementById("text1").value,document.getElementById("text2").value)'></input>
</p>
</body>
</html>
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
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;
}