0

I'm trying to get a number from an input box, but it returns an empty string as an alert. What do I miss?

var button = document.getElementsByClassName("btn")[0];
var num = document.getElementById("input").value;
button.addEventListener("click", calculate);

function calculate() {
    alert(num);
}
<input type="number" id="input">
<input type="button" value="Calculate!" class="btn">
<p id="result">

2
  • Your num variable holds what the input field contained at the time this line of code was executed, it does not get updated automatically. You want to read the field value inside your handler function ... Commented Dec 15, 2017 at 21:51
  • Try declaring var num = ... inside function calculate() { ... } Commented Dec 15, 2017 at 21:52

4 Answers 4

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

-1

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/

1 Comment

I don't like adding too much atributes to HTML elements.
-1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.