Search code examples
javascripthtmlgetelementbyid

Can't Get Value of Input it JavaScript


I'm trying to store the value of a text input, but when I console.log the variable it is undefined.The function getInfo() is in the script referenced at the top and is called near the bottom in an "onClick".

function:

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

and the 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>

Solution

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

    This asks to get the value of "gamePin" element by ID which is why you get undefined.

    If you want to get the value of the input field. You need to get the element of the input field by providing it an Id. Try this.

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

    Now this works.

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