Number from input box Javascript

后端 未结 4 504
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 12:02

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

相关标签:
4条回答
  • 2021-01-28 12:31

    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/

    0 讨论(0)
  • 2021-01-28 12:45

    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/

    0 讨论(0)
  • 2021-01-28 12:51

    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);
    }
    
    0 讨论(0)
  • 2021-01-28 12:53

    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.

    0 讨论(0)
提交回复
热议问题