[英]How do I take the value of a date input and save it to a global variable?
I got the value of the date input field but now I want to take that value and put it into a global variable. 我得到了日期输入字段的值,但是现在我想将该值放入一个全局变量中。 How do I do that? 我怎么做?
const moment = require("moment");
//current Date
let date = moment().format("YYYY-MM-DD");
//selecting input date
let datepick = document.getElementById("datepicker");
//setting value of date input to current date
datepick.value = date;
//global variable to save the new selected value of the input date field
let selectedDate;
//getting the value on change of the input date field
document.getElementById("datepicker").addEventListener("change", function() {
var selectedDate = this.value;
});
You have the global newSelectedDate
variable. 您具有全局newSelectedDate
变量。 You should use that variable instead of selectedDate
. 您应该使用该变量而不是selectedDate
。
Now do keep in mind that the newSelectedDate
is initially undefined
, so logging it instantly won't return a value. 现在请记住, newSelectedDate
最初是undefined
,因此立即对其进行记录不会返回任何值。 Only after the change
event has occurred will the newSelectedDate
have a value. 仅在发生change
事件之后, newSelectedDate
才具有值。
let newSelectedDate; // undefined
document.getElementById("datepicker").addEventListener("change", function() {
newSelectedDate = this.value; // Update newSelectedDate value.
console.log(newSelectedDate) // Now has a string.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.