简体   繁体   English

如何获取日期输入的值并将其保存到全局变量?

[英]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.

相关问题 我如何使用 JavaScript 将输入从文本框中获取到变量然后打印变量的值? - How do i use JavaScript to take the input from a text box to a variable then print the value of a variable? 如何获取用户的输入并返回已定义的匹配变量的值? - How do I take a user's input and return the value of a matching variable I have defined? 如何保存 ajax json 对全局变量的响应以供重用 - How do I save ajax json response to global variable for reuse 如何获取输入值并将其放入angularJS中的变量? - How can I take a input value and put into a variable in angularJS? 如何获取日期输入的值? - How do I grab the value of a date input? 如何获取用户输入并将其永久保存在变量中并在 window.open() 中使用该变量 - How can i take user input and save it permanently in a variable and use that variable in window.open() 如何获取输入字段的值并使用它来过滤数组? - How do I take the value of an input field and use it to filter an array? 如何获取输入值并将其附加到新元素? - How do I take input value and append it to new element? 如何在函数中保存全局变量值? - How to save global variable value within function? 如何在变量中保存INPUT的值? - How to save the value of INPUT in variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM