简体   繁体   中英

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)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM