AJlearn
AJlearn

Reputation: 5

Number from input box Javascript

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">

Upvotes: 0

Views: 71

Answers (4)

David Anthony Acosta
David Anthony Acosta

Reputation: 4890

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/

Upvotes: -1

David Anthony Acosta
David Anthony Acosta

Reputation: 4890

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/

Upvotes: -1

Lucy
Lucy

Reputation: 73

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);
}

Upvotes: 2

Quentin
Quentin

Reputation: 943152

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.

Upvotes: 1

Related Questions