I'm working on a small HTML and JavaScript project, and I'm encountering an issue with converting strings to numbers. I have an input field in my HTML where users can enter a number as a string. I'm using JavaScript to convert this string to a number and perform calculations, but I'm not getting the expected results.
Here's my HTML and JavaScript code:
When I enter a number into the input field and click the "Calculate" button, the result is not as expected. For instance, if I enter "5", the result displayed is "510" instead of "15".
Could someone explain why this is happening? Am I missing something in my code? How can I ensure that the string is correctly converted to a number before performing calculations? Any insights or code modifications would be greatly appreciated. Thank you!
Here's my HTML and JavaScript code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>String to Number Conversion</title>
</head>
<body>
<input type="text" id="numberInput" placeholder="Enter a number">
<button onclick="calculate()">Calculate</button>
<p id="result"></p>
<script>
function calculate() {
let input = document.getElementById("numberInput").value;
let convertedNumber = Number(input);
let result = convertedNumber + 10;
document.getElementById("result").textContent = "Result: " + result;
}
</script>
</body>
</html>
Could someone explain why this is happening? Am I missing something in my code? How can I ensure that the string is correctly converted to a number before performing calculations? Any insights or code modifications would be greatly appreciated. Thank you!