JavaScript regarding string and integer value - javascript

i need to help to learn this. Thanks in advance.
<label>Value 1</label> <input type="text" id="value1" name="value1" /><br />
<script>
var num1 = document.getElementById("value1");
parseInt(num1.value) // this gives an integer when you key in an integer in the input box.
var num1 = document.getElementById("value1").value;
parseInt(num1) // this gives NaN when you key in an integer in the input box.
</script>
May i know why is there a difference between them? I thought that they are the same but it's not.

From your new post (You posted as an answer, which is deleted now), You are trying to get the value from the input field before the values are inserted.
Move these lines to inside function add, so that value as assigned to variables only after clicking the button.
var num1 = document.getElementById("value1").value;
var num2 = document.getElementById("value2").value;
The function should be like
function add () {
var num1 = document.getElementById("value1").value;
var num2 = document.getElementById("value2").value;
var sumup = parseInt(num1.value) + parseInt(num2.value);
document.getElementById("output").innerHTML = "The total is " + sumup;
}
And the answer for your question is there is no difference between
var num1 = document.getElementById("value1");
parseInt(num1.value)
and
var num1 = document.getElementById("value1").value;
parseInt(num1)
Check the snippet below
<form action="" name="add1">
<label>Value 1</label>
<input type="text" id="value1" name="value1" />
<br />
<label>Value 2</label>
<input type="text" id="value2" name="value2" />
<br />
<br />
<div id="output"></div>
<br />
<button type="button" id="addup">Add</button>
</form>
<script>
document.getElementById("addup").addEventListener("click", add);
function add() {
var num1 = document.getElementById("value1").value;
var num2 = document.getElementById("value2").value;
var sumup = parseInt(num1) + parseInt(num2);
document.getElementById("output").innerHTML = "The total is " + sumup;
}
</script>

Both examples seem equivalent, something else is wrong. Maybe you are overwriting num1 variable? Try this:
var num1 = document.getElementById("value1");
parseInt(num1.value) // this gives an integer when you key in an integer in the input box.
var num2 = document.getElementById("value1").value;
parseInt(num2) // this gives NaN when you key in an integer in the input box.

Related

I started learning JavaScript and I have a problem with if statement

I started learning JavaScript and I want to do my own small project 'BMI calculator' but I can't find an error with my if statement.
Everything working fine but if as a input I will type for example 0, I don't see any warning message instead I see result of calculation.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input id="height">
<br> Weight: <input id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>
Because you don't stop the function when you detect invalid input. You put the error message into the message panel, but then you continue to the code that performs the calculation with the invalid input.
You should return from the function after displaying the error message.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
return;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
return;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input type="number" id="height">
<br> Weight: <input type="number" id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>

Javascript displaying but not calulating [duplicate]

I am adding two numbers, but I don't get a correct value.
For example, doing 1 + 2 returns 12 and not 3
What am I doing wrong in this code?
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = y + z;
document.getElementById("demo").innerHTML = x;
}
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +:
var x = +y + +z;
I just use Number():
var i=2;
var j=3;
var k = Number(i) + Number(j); // 5
You need to use javaScript's parseInt() method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".
Use parseInt(...) but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).
var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);
alert(x + y);
Hope this helps!
The following may be useful in general terms.
First, HTML form fields are limited to text. That applies especially to text boxes, even if you have taken pains to ensure that the value looks like a number.
Second, JavaScript, for better or worse, has overloaded the + operator with two meanings: it adds numbers, and it concatenates strings. It has a preference for concatenation, so even an expression like 3+'4' will be treated as concatenation.
Third, JavaScript will attempt to change types dynamically if it can, and if it needs to. For example '2'*'3' will change both types to numbers, since you can’t multiply strings. If one of them is incompatible, you will get NaN, Not a Number.
Your problem occurs because the data coming from the form is regarded as a string, and the + will therefore concatenate rather than add.
When reading supposedly numeric data from a form, you should always push it through parseInt() or parseFloat(), depending on whether you want an integer or a decimal.
Note that neither function truly converts a string to a number. Instead, it will parse the string from left to right until it gets to an invalid numeric character or to the end and convert what has been accepted. In the case of parseFloat, that includes one decimal point, but not two.
Anything after the valid number is simply ignored. They both fail if the string doesn’t even start off as a number. Then you will get NaN.
A good general purpose technique for numbers from forms is something like this:
var data=parseInt(form.elements['data'].value); // or parseFloat
If you’re prepared to coalesce an invalid string to 0, you can use:
var data=parseInt(form.elements['data'].value) || 0;
Just add a simple type casting method as the input is taken in text. Use the following:
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
This won't sum up the number; instead it will concatenate it:
var x = y + z;
You need to do:
var x = (y)+(z);
You must use parseInt in order to specify the operation on numbers. Example:
var x = parseInt(y) + parseInt(z); [final soulution, as everything us]
Simple
var result = parseInt("1") + parseInt("2");
console.log(result ); // Outputs 3
This code sums both the variables! Put it into your function
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`
<head>
<script type="text/javascript">
function addition()
{
var a = parseInt(form.input1.value);
var b = parseInt(form.input2.value);
var c = a+b
document.write(c);
}
</script>
</head>
<body>
<form name="form" method="GET">
<input type="text" name="input1" value=20><br>
<input type="text" name="input2" value=10><br>
<input type="button" value="ADD" onclick="addition()">
</form>
</body>
</html>
Or you could simply initialize
var x = 0; ( you should use let x = 0;)
This way it will add not concatenate.
If Nothing works then only try this. This maybe isn't Right way of doing it but it worked for me when all the above failed.
var1 - (- var2)
You are missing the type conversion during the addition step...
var x = y + z; should be var x = parseInt(y) + parseInt(z);
<!DOCTYPE html>
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction()
{
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = parseInt(y) + parseInt(z);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
<input type="text" name="num1" id="num1" onkeyup="sum()">
<input type="text" name="num2" id="num2" onkeyup="sum()">
<input type="text" name="num2" id="result">
<script>
function sum()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
if (number1 == '') {
number1 = 0
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
else if(number2 == '')
{
number2 = 0;
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
else
{
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
}
</script>
It's very simple:
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Add Section</p>
<label>First Number:</label>
<input id="txt1" type="text"/><br />
<label>Second Number:</label>
<input id="txt2" type="text"/><br />
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
If we have two input fields then get the values from input fields, and then add them using JavaScript.
$('input[name="yourname"]').keyup(function(event) {
/* Act on the event */
var value1 = $(this).val();
var value2 = $('input[name="secondName"]').val();
var roundofa = +value2+ +value1;
$('input[name="total"]').val(addition);
});
This can also be achieved with a more native HTML solution by using the output element.
<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
<input type="number" id="a" name="a" value="10" /> +
<input type="number" id="b" name="b" value="50" /> =
<output name="result" for="a b">60</output>
</form>
https://jsfiddle.net/gxu1rtqL/
The output element can serve as a container element for a calculation or output of a user's action. You can also change the HTML type from number to range and keep the same code and functionality with a different UI element, as shown below.
<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
<input type="range" id="a" name="a" value="10" /> +
<input type="number" id="b" name="b" value="50" /> =
<output name="result" for="a b">60</output>
</form>
https://jsfiddle.net/gxu1rtqL/2/
You can do a precheck with regular expression wheather they are numbers as like
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
if((x.search(/[^0-9]/g) != -1)&&(y.search(/[^0-9]/g) != -1))
var x = Number(y)+ Number(z);
else
alert("invalid values....");
document.getElementById("demo").innerHTML = x;
}
Use parseFloat it will convert string to number including decimal values.
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = parseFloat(y) + parseFloat(z);
document.getElementById("demo").innerHTML = x;
}
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
You can also write :
var z = x - -y ;
And you get correct answer.
<body>
<input type="text" id="number1" name="">
<input type="text" id="number2" name="">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, y ;
x = document.getElementById('number1').value;
y = document.getElementById('number2').value;
var z = x - -y ;
document.getElementById('demo').innerHTML = z;
}
</script>
</body>
Here goes your code by parsing the variables in the function.
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">
<br>Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Answer
An alternative solution, just sharing :) :
var result=eval(num1)+eval(num2);
Perhaps you could use this function to add numbers:
function calculate(a, b) {
return a + b
}
console.log(calculate(5, 6))

Why doesn't this simple HTML/JavaScript calculator work?

Here is my code:
<!DOCTYPE html>
<html>
<header></header>
<body>
<label id="FirstNumber">First Number:</label>
<input type="text" id="number1">
<br>
<label id="SecondNumber">Second Number:</label>
<input type="text" id="number2">
<br>
<button id="add" onclick="add()">Add</button>
<button id="multiply" onclick="multiply()">Multiply</button>
<br>
<label id="FinalNumberLabel">Answer:</label>
<label id="Answer"></label>
<script type="text/javascript">
function add() {
var num1 = document.getElementById("number1");
var num2 = document.getElementById("number2");
var answer = num1 + num2;
document.getElementById("Answer").innerHTML = answer;
}
function multiply() {
var num1 = document.getElementById("number1");
var num2 = document.getElementById("number2");
var answer = num1 * num2;
document.getElementById("Answer").innerHTML = answer;
}
</script>
</body>
</html>
The "Multiply" button returns a "NaN" error and the Add button always returns "[objectHTMLInputElement][objectHTMLInputElement]"
Why doesn't this work?
You're not getting the values, just the elements:
var num1 = document.getElementById("number1");
In this case num1 isn't actually a number, it's an objectHTMLInputElement.
You probably want to start with something like:
var num1 = parseFloat(document.getElementById("number1").value);
Perhaps also add some error checking, or specify that the inputs need to be numeric, etc.
.value -> you do not want the input element, you want the value it holds
parseInt -> you want number not string (or parseFloat if you want floats)
function add() {
var num1 = parseInt(document.getElementById("number1").value);
var num2 = parseInt(document.getElementById("number2").value);
var answer = num1 + num2;
document.getElementById("Answer").innerHTML = answer;
}
function multiply() {
var num1 = parseInt(document.getElementById("number1").value);
var num2 = parseInt(document.getElementById("number2").value);
var answer = num1 * num2;
document.getElementById("Answer").innerHTML = answer;
}

Javascript Two calculators on one site

Hi i have this code on my site`
<body>
<script>
function calcResult() {
document.getElementById('result').innerHTML = '';
var num1 = new Number(document.getElementById('txt1').value);
var num2 = new Number(document.getElementById('txt2').value);
if (isNaN(num1) || isNaN(num2)) {
alert('One or both inputs are not a number');
} else {
document.getElementById('result').innerHTML = num1 * num2;
}
}
window.onload = function() {
document.getElementById('btnCalc').onclick = calcResult;
}
</script>
<div>
Enter value 1
<input type="text" id="txt1" />
<br />Enter value 2
<input type="text" id="txt2" />
<br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<script>
function test() {
document.getElementById('re').innerHTML = '';
var n1 = new Number(document.getElementById('od1').value);
var n2 = new Number(document.getElementById('od2').value);
if (isNaN(n1) || isNaN(n2)) {
alert('One or both inputs are not a number');
} else {
document.getElementById('re').innerHTML = n1 - n2;
}
}
window.onload = function() {
document.getElementById('od').onclick = test;
}
</script>
<div>
Enter value 1
<input type="text" id="od1" />
<br />Enter value 2
<input type="text" id="od2" />
<br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
</body>
The problem is that first form isnt working and the second is working. On my site i want many of these calculator, but i dont know why is not working. I will be gradefull if someone help me find result.
Write all javascript code in one script tag. Try the following code
<body>
<script>
function calcResult(){
document.getElementById('result').innerHTML = '';
var num1 = new Number(document.getElementById('txt1').value);
var num2 = new Number(document.getElementById('txt2').value);
if(isNaN(num1) || isNaN(num2)){
alert('One or both inputs are not a number');
} else {
document.getElementById('result').innerHTML = num1 * num2;
}
}
function test(){
document.getElementById('re').innerHTML = '';
var n1 = new Number(document.getElementById('od1').value);
var n2 = new Number(document.getElementById('od2').value);
if(isNaN(n1) || isNaN(n2)){
alert('One or both inputs are not a number');
} else {
document.getElementById('re').innerHTML = n1 - n2;
}
}
window.onload=function(){
document.getElementById('btnCalc').onclick = calcResult;
document.getElementById('od').onclick = test;
}
</script>
<div>
Enter value 1 <input type="text" id="txt1" /><br />
Enter value 2 <input type="text" id="txt2" /><br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<div>
Enter value 1 <input type="text" id="od1" /><br />
Enter value 2 <input type="text" id="od2" /><br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
</body>
If both functions are equal (you just want to execute three diference elements),
use element's Ids as parameters in function argument and call it as often as you wish with any diference Id.
<body>
<script>
<div>
Enter value 1 <input type="text" id="txt1" /><br />
Enter value 2 <input type="text" id="txt2" /><br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<script>
function test(id){
document.getElementById(id, id2, id3).innerHTML = '';
var n1 = new Number(document.getElementById(id2).value);
var n2 = new Number(document.getElementById(id3).value);
if(isNaN(n1) || isNaN(n2)){
alert('One or both inputs are not a number');
} else {
document.getElementById(id).innerHTML = n1 - n2;
}
}
window.onload=function(){
document.getElementById('btnCalc').onclick = function(){ test("result", "txt1", "txt2") };
document.getElementById('od').onclick = function(){ test("re", "od1", "od2") };
}
</script>
<div>
Enter value 1 <input type="text" id="od1" /><br />
Enter value 2 <input type="text" id="od2" /><br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
<script type="text/javascript">
function calcResult(resultId, valId, val2Id, operation) {
var $result = document.getElementById(resultId);
$result.innerHTML = '';
var num1 = new Number(document.getElementById(valId).value);
var num2 = new Number(document.getElementById(val2Id).value);
if (isNaN(num1) || isNaN(num2)) {
alert('One or both inputs are not a number');
} else {
$result.innerHTML = operation(num1, num2);
}
}
window.onload = function() {
document.getElementById('btnCalc').onclick = function() {
calcResult('result', 'txt1', 'txt2', function(num1, num2) {
return num1 * num2;
});
}
document.getElementById('od').onclick = function() {
calcResult('re', 'od1', 'od2', function(num1, num2) {
return num1 - num2;
});
};
}
</script>
Put all the scripts in one <script> tag.
Also, there's a room for improvement on your program. see below:
i can see that eventhough your button is named "calculate difference",
the first form is calculating the product and the second form is calculating the difference, thus, using this,
you can rewrite your code in such a way that you only have one function for both operations,
just pass the elementIds as parameters and a function which takes care which operation to apply. like the one I wrote above.
see it here: http://jsfiddle.net/1yo4ypc2/

how can i get total of two numbers using javascript

I'm using this form script to automatically calculate totals. Now I need to get that total and print it.
Here is my code.
function myFunction()
{
var x = document.getElementById("frm1");
var txt1 =x.elements[0].value;
var txt2 =x.elements[1].value;
var total =txt1+txt2;
document.getElementById("demo").innerHTML="total is :"+total;
}
<body>
<form id="frm1">
First value : <input type="text" name="first"><br>
Second Value : <input type="text" name="second"><br>
</form>
<p id="demo"></p>
<button onclick="myFunction()"> ADD </button>
</body>
It doesn't really say, but I'm guessing you're talking about numbers, if so parse the string values as numbers before you add them up
function myFunction() {
var x = document.getElementById("frm1");
var txt1 = parseFloat( x.elements[0].value );
var txt2 = parseFloat( x.elements[1].value );
var total = txt1 + txt2;
document.getElementById("demo").innerHTML = "total is :"+total;
}
FIDDLE

Categories