0

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;
});
Satrogan
  • 469
  • 3
  • 7
  • 16
  • 2
    Get rid of `var` before `selectedDate`, so you assign the global variable instead of declaring a local variable. – Barmar Sep 09 '19 at 19:16
  • i did that, however, when i logged it to the console it comes back as undefined – Satrogan Sep 09 '19 at 19:20
  • The variable is only assigned when you change the datepicker. Did you wait until then to log it? – Barmar Sep 09 '19 at 19:28
  • the global varibable \\ let selectedDate; is what im saving the value to. i console.log(selectedDate) after /outside of document.getElementById("datepicker").addEventListener("change", function() { selectedDate = this.value; }); – Satrogan Sep 09 '19 at 19:31
  • You should log it inside the change event. – callback Sep 09 '19 at 19:31
  • i want to log the variable in the global scope so that i can use the value.... globally – Satrogan Sep 09 '19 at 19:33
  • That doesn't wait for the change event, it logs it immediately when the page is loaded. – Barmar Sep 09 '19 at 19:33
  • You can't use it globally, since global code runs when the page is first loaded, not when the user does something. You can use it in another event listener, like the one that makes an AJAX request when the user clicks the Submit button. – Barmar Sep 09 '19 at 19:34
  • See https://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron – Barmar Sep 09 '19 at 19:34
  • i want the value so that i can use it as a parameter in a fetch call, i understand what you mean. thanks ill write back if it works – Satrogan Sep 09 '19 at 19:35

1 Answers1

0

You have the global newSelectedDate variable. You should use that variable instead of selectedDate.

Now do keep in mind that the newSelectedDate is initially undefined, so logging it instantly won't return a value. Only after the change event has occurred will the newSelectedDate have a value.

let newSelectedDate; // undefined

document.getElementById("datepicker").addEventListener("change", function() {
  newSelectedDate = this.value; // Update newSelectedDate value.
  console.log(newSelectedDate) // Now has a string.
});
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32