I am using this code and it gives 0
answer every time when I click on Button.
Here is The code.
<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
<script>
var f = document.getElementById('first').value;
var s = document.getElementById('second').value;
var ans = document.getElementById('ans');
var b = document.getElementById('btn');
b.onclick = function() {
ans.value = f * s;
}
</script>
It is because when you put text in an input it returns a string. A string is text. In order to make text into a number, put it inside a
parseFloat()
function. Also, put the onclick in the HTML. Also, you need to get the values in the function, because when the page loads, the inputs are empty, but when you click the button the user will have typed in the numbers. Also, if the value is empty it will return NaN. You need to check if the value is not equal to a string that cannot be converted to a number.Try this: