无法获取输入值 JavaScript

Can't Get Value of Input it JavaScript

我正在尝试存储文本输入的值,但是当我 console.log 变量是 undefined.The 函数 getInfo() 在顶部引用的脚本中并被调用"onClick".

底部附近

函数:

function getInfo() {
  var gamePin = document.getElementById("gamePin").value;
  console.log(gamePin); //undefined??
}

和HTML:

<!DOCTYPE html>
<html>
<head>
  <title>KBot</title>
  <link href="style.css" rel="stylesheet" type="text/css"> 
  <link rel="shortcut icon" type="image/png" href="favicon.png"/>
  <script src="script.js"></script>
</head>
  <body>
    <header>
      KBOT - Spam bot for Kahoot
    </header>
      <div class="box">
        <h2>Enter Info</h2>
        <form>
          <div class="inputBox" id="gamePin">
            <input type="text" name="" required="">
            <label>Game Pin</label>
          </div>
          <div class="inputBox" id="botName">
            <input type="text" name="" required="">
            <label>Bot Name</label>
          </div>
          <div class="inputBox" id="botAmount">
              <input type="text" name="" required="">
              <label>Bot Amount (Up To 100)</label>
          </div>
          <input type="button" id="submit" value="Release the bots!" 
        onClick="getInfo()">
      </form>
    </div>
  </body>
</html>
function getInfo() {
  var gamePin = document.getElementById("gamePin").value;
  console.log(gamePin); //undefined??
}

这要求通过 ID 获取 "gamePin" 元素的值,这就是为什么你得到未定义的原因。

如果你想获取输入域的值。您需要通过提供一个 Id 来获取输入字段的元素。试试这个。

<div class="inputBox" >
            <input type="text" name="gamePin" id="gamePin" required="">
            <label>Game Pin</label>
          </div>

现在可以了。

function getInfo() {
  var gamePin = document.getElementById("gamePin").value;
  console.log(gamePin);
}