Consider the code I have:
var g = document.getElementById("al").value;
function start() {
document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
}
<p id="test2">Output is here:</p>
<form>
<label for="g">a:</label>
<input type="number" id="al" name="g" placeholder="Enter a" value="55">
<button onclick="start()" type="button">Here</button>
</form>
The output I get on clicking the button is string55, whatever the user input is. I want to fix it and replace 55 with user’s actual input. What is the fix then?
2
Answers
You need to grab the value from within the function:
PS, using inline HTML
on*
handlers is considered bad programming habit. It’s hard to debug. JS should be in one place only, instead, useElement.addEventListener()
The following line already gets the user’s input.
So
console.log(g);
will print the user’s input in the web console.You always want to use the
typeof
operator andparseFloat
the input, here we go.