I\'m trying to get a number from an input box, but it returns an empty string as an alert. What do I miss?
Then i guess you could do this way to avoid adding attributes.
<input type="number" id="input">
<input type="button" value="Calculate!" class="btn">
<p id="result"></p>
<script>
var button = document.getElementsByClassName("btn")[0];
button.addEventListener('click', function() {
calculate();
});
function calculate() {
var num = document.getElementById("input").value;
alert(num);
document.getElementById("result").innerHTML = num;
}
</script>
Working example: https://jsfiddle.net/j9eb0xfm/5/
Why don't you instead do it like this?
<input type="number" id="input">
<input type="button" onclick="calculate()" value="Calculate!" class="btn">
<p id="result"></p>
<script>
function calculate() {
var num = document.getElementById("input").value;
alert(num);
document.getElementById("result").innerHTML = num;
}
</script>
Working example: https://jsfiddle.net/j9eb0xfm/3/
You need to read the value of the input inside the function, not during page load. The following code will work.
var button = document.getElementsByClassName("btn")[0];
button.addEventListener("click", calculate);
function calculate() {
var num = document.getElementById("input").value;
alert(num);
}
You read the value of the input as the page loads (when it has its default value, which is an empty string).
You then alert the results of that read when the function runs.
You need to read the value inside the function so that you get the value at the time the function runs.