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);
Related
.toFixed is not working in my code. I am using it with .toLocaleString()
JS / Fiddle: https://jsfiddle.net/8b6t90f5/
$(function() {
var value = 5000.3269588;
$("#process").click(function() {
$('#amount').text("Total: $" + value.toLocaleString().toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="amount"></div>
<input id="process" class="button_text" type="submit" name="submit" value="SHOW VALUE">
Strings do not have a toFixed(), only numbers do.
$('#amount').text("Total: " + value.toLocaleString("en-US", {maximumFractionDigits:2, currency:"USD", style:"currency"}));
is possibly what you're after.
toFixed() is a Number method. toLocaleString() turns it into a string. You need to use toFixed() first, then parse that back to float and use toLocaleString():
parseFloat(value.toFixed(2)).toLocalString('en-BR');
const num = 50023.357289357;
console.log(parseFloat(num.toFixed(2)).toLocaleString());
You continue to use string methods for numbers and vice versa. Try this:
const num = 5000.3269588;
console.log(num.toLocaleString(undefined, {maximumFractionDigits: 2}));
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 currently working on a little programming task for school. I chose the task because I had an idea how to get the core of the program running in Java, but I'm having issues translating this into a very simple web page, no experience with HTML or JS.
My issue is: I'm receiving input via a button. When clicked, a function is called and that function gets the value of the input. However, all I get as the alert window is objectHTMLinputElement. What am I doing wrong?
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH() {
var risikoHoehe = parseInt(document.getElementById('input2')).value;
alert(input2);
}
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
Get the value of the input before parsing it. Plus, you are alerting an input element instead of the variable that you are setting the value to. Use:
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
Change this part parseInt(document.getElementById('input2')).value; as :
parseInt(document.getElementById('input2').value)
You're calling the wrong variable, try 'risikoHoehe' instead of 'input2':
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
}
function myRH(){
var risikoHoehe = document.getElementById('input2').value;
alert(risikoHoehe);
}
1) You are trying to parse a DOM element to an int so it returns undefined.
Use document.getElementById('input2').value.
2) Use parseInt only if needed, if its just for alerting then you can skip it
3) You cannot directly refer to an dom element by id, you have to get that element in a variable and then use it.
alert(input2); should be alert(risikoHoehe);
Well, Here is the complete working code-
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myRT() {
var risikoTraeger=document.getElementById('input1').value;
alert(risikoTraeger);
}
function myRH(){
var risikoHoehe = parseInt(document.getElementById('input2').value);
alert(risikoHoehe);
}
</script>
</head>
<body>
<h1>Siemens: Risikoassessment</h1>
<p id="demo">How many entries?</p>
<input type="text" id="input1" />
<button type="button" onclick="myRT()">Risk carrier</button>
</br>
<input type="text" id="input2" />
<button type="button" onclick="myRH()">Sum of the risk</button>
</body>
</html>
Hoping this will help you :)
Let's see what you are doing wrong:
var risikoHoehe = parseInt(document.getElementById('input2')).value;
document
document itself
getElementById()
the function which gives us the element that has the specific ID parameter
'input2'
the ID of the desired input
.value
the element's value if it has any.
parseInt()
the function that converts any string to it's integer value.
now look at here:
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
parseInt(objectHTMLInputElement) => what can we get if we try to convert the html input element to an integer?
(integer).value => does integers have value property?
But if you write it like this:
var risikoHoehe = parseInt(document.getElementById('input2').value);
document.getElementById('input2') => the input element itself (objectHTMLInputElement)
objectHTMLInputElement.value => the value of the input as string
parseInt(string) => Parse the integer value of the string
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 have a question regarding the add sign in JavaScript I'm a bit confused on this. I have this input text box which I will be input as 50 and it will add plus 50 . My result in adding the numbers which for example I input 50 the result is 5050 which is totally wrong. Can someone help me on this?
<!DOCTYPE html>
<html>
<head>
<title>activity 2</title>
<script type="text/javascript">
function computeSalary(){
var salaryData = document.form1.salary.value;
var salary1 = salaryData + 50;
document.form1.newSalary.value = salary1;
}
</script>
</head>
<body>
<form name="form1">
Enter the daily salary:
<input type="text" name="salary" /><br />
<input type="button" value="Compute" onClick="computeSalary();" /><br />
<br />
The new salary: <input type="text" name="newSalary" />
</form>
</body>
</html>
You can convert the string value you're getting, which is being concatenated to your value, to a number by simply adding a plus sign:
var salary1 = +salaryData + 50;
jsFiddle example
You have to convert the value you got from the input control to float or integer before adding it using the + operator. The + operator will convert both operands to a same type before adding both operands. This is the primary reason why you got 5050 because the 50 of type int got converted to string.
use this code:
function computeSalary(){
var salaryData = document.form1.salary.value;
var salary1 = parseFloat(salaryData) + 50;
document.form1.newSalary.value = salary1;
}
Change the following line:
var salary1 = parseInt(salaryData) + 50; // Use parseInt or parseFloat
The reason is that JavaScript will coerce strings and integers into strings. So your integer 50 is converted to a string and then concatenated.