简体   繁体   English

将 html 表单数据传递给 JavaScript 变量

[英]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.我想从我的日期输入中获取存储在表单中的信息,并将其发送到 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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