The reason is that when you click the button in your original code it gets executed with 0 values because you have not asked them to get initiated after each button click. So what you are trying to do is just that both first and second text fileds will get their values in the initial page load this means those values are empty. So then when you click the button it get current values(0) and multiple. So its always 0.
In below example what @Jacob doing is he first get the target button via var b = document.getElementById('btn');
and then he have wrapped the variables inside click function . So each time you click the button and function get called and each variable get current values.
At last what he did is that he when you click the button he asks for each button current values . So it also get the current value from the elements.
Just move the onclick like up, so it gets the new values when the user clicks.
<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
<script>
var b = document.getElementById('btn');
b.onclick = function() {
var f = document.getElementById('first').value;
var s = document.getElementById('second').value;
var ans = document.getElementById('ans');
ans.value = f * s;
}
</script>
Or to only get the elements once.
<input type="text" id="first">
<input type="text" id="second">
<input type="text" id="ans">
<button id="btn">Count</button>
<script>
var b = document.getElementById('btn');
var f = document.getElementById('first');
var s = document.getElementById('second');
var ans = document.getElementById('ans');
b.onclick = function() {
ans.value = f.value * s.value;
}
</script>