Issue
I am having trouble assigning a number from a text input which type is "text" (I know I can use number type but this is requested) to calculate the value and set that value to another text input
This is what my HTML file look like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<script src="./ind.js"></script>
<title>Document</title>
</head>
<body>
Input: <input id="txtInput" type="text">
<input onclick="showResult()" type="button" value="Show Result"> <br> <br>
The number after adding 10 is:
<input id="result" type="text">
</body>
</html>
And my JavaScript code:
var input = document.getElementById("txtInput").value;
var result = document.getElementById("result").value;
function showResult(){
result.value = input + 10;
}
I tried casting the assigned value with Number() method like this:
var input = Number(document.getElementById("txtInput").value);
var result = document.getElementById("result").value;
function showResult(){
result.value = input + 10;
}
But it didn’t work out.
What am I doing wrong, I’m new to JS and StackOverFlow, also my English is bad, please guide me.
Solution
The problem was that the variables were outside the function, and to cast the input to number you can use the parseInt() or parseFloat() functions.
function showResult(){
var input = document.getElementById("txtInput").value;
var result = document.getElementById("result");
result.value = parseInt(input) + 10
}
It could also be used as follows using the two variables as globals:
const input = document.getElementById("txtInput");
const result = document.getElementById("result");
function showResult(){
result.value = parseInt(input.value) + 10
}
Answered By – Andriu1510
Answer Checked By – Cary Denson (BugsFixing Admin)