如何获取javascript的输入值

时间:2019-05-24 19:53:33

标签: javascript html

我目前正在尝试获取用户选择的输入字段的值作为他们的电话号码,但是由于某种原因,我无法这样做。

我已经尝试过将其设置为id,然后执行document.getElementById("testing").value,但没有成功。

这是我当前的代码:

<section class="generate">
  <div class="container">
    <h3>Generate a number between </h3>
    <form>
      First number
      <input id="testing" type="number" name="firstnumber" value="First number">
      <br> Second number
      <input type="number" name="secondnumber" value="Second number">
      <br>
      <input type="submit" value="Generate random number">
      <script>
        var secondNumber = document.getElementById('testing').value
        var randomNumber = Math.floor(Math.random() * secondNumber);
        console.log(randomNumber);
        console.log(secondNumber);
      </script>
    </form>
  </div>
</section>

2 个答案:

答案 0 :(得分:1)

您需要在事件监听器中运行代码,而不是在页面首次加载时运行。

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault(); // prevent form from really submitting
  var secondNumber = document.getElementById('testing').value
  var randomNumber = Math.floor(Math.random() * secondNumber);
  console.log(randomNumber);
  console.log(secondNumber);
});
<section class="generate">
  <div class="container">
    <h3>Generate a number between </h3>
    <form>
      First number
      <input id="testing" type="number" name="firstnumber" value="First number">
      <br> Second number
      <input type="number" name="secondnumber" value="Second number">
      <br>
      <input type="submit" value="Generate random number">
    </form>
  </div>
</section>

答案 1 :(得分:0)

<section class="generate">
  <div class="container">
    <h3>Generate a number between </h3>
    <form onsubmit="return false">
      First number
      <input id="firstnumber" type="number" name="firstnumber" >
      <br> Second number
      <input id="secondnumber" type="number" name="secondnumber" >
      <br>
      <input type="submit" onclick="generate()" value="Generate random number">
      <script>
  function generate(){
        var firstnumber = document.getElementById('firstnumber').value
         var secondnumber =document.getElementById('secondnumber').value
        var randomNumber = Math.floor(Math.random() * secondnumber);
        console.log(randomNumber);
        console.log(firstnumber);
        console.log(secondnumber);}
      </script>
    </form>
  </div>
</section>