bernard
bernard

Reputation: 51

Passing html form data to JavaScript variable

I would like to take the information stored in the form from my date input and send it to a variable in JavaScript.

<body>
    <form action="" method="get" class="countdown">
        <div class="countdown">
            <label for="birthday">Enter your birthday: </label>
            <input type="date" name="birthday" id="birthday" required>
        </div>
        <div class="countdown">
            <input type="submit" value="Submit"
        </div>
    </form>
    
    
    
<script src="lab3.js"></script>
</body>

var bDay = document.getElementById("birthday").value
console.log(bDay)

Upvotes: 1

Views: 1252

Answers (1)

Seth B
Seth B

Reputation: 1056

You'll want to do something like this:

//Wait for page to finish loading
window.addEventListener("load",function(){
  //Run function when you submit form
  document.getElementById("form").addEventListener("submit",function(e){
    //Stop the form from submitting:
    e.preventDefault();

    //Get your input value
    var bDay = document.getElementById("birthday").value;

    //Log it to your console
    console.log(bDay)
  });
});
<!DOCTYPE html>
<html>
  <body>
    <!-- Add an id to your form-->
    <form id='form' action="" method="get" class="countdown">
      <div class="countdown">
        <label for="birthday">Enter your birthday: </label>
        <input type="date" name="birthday" id="birthday" required>
      </div>
      <div class="countdown">
        <input type="submit" value="Submit">
      </div>
    </form>
    <!-- <script src="lab3.js"></script> -->
  </body>
</html>

Upvotes: 3

Related Questions