Skip to content Skip to sidebar Skip to footer

Javascript - Get A Date From An HTML Input

I am currently trying to take the value from an HTML input (below) and put it into a javascript variable so I can use it for other thing

Solution 1:

document.getElementById("dateInput").addEventListener("change", function() {
    var input = this.value;
    var dateEntered = new Date(input);
    console.log(input); //e.g. 2015-11-13
    console.log(dateEntered); //e.g. Fri Nov 13 2015 00:00:00 GMT+0000 (GMT Standard Time)
});

Basically you need to listen for the change of your date input, currently you were trying to get the value on load, when the picker has no date in it hence you get 'Invalid Date'


Solution 2:

Make sure your script is executing after the DOM has fully loaded. To do this you can put your JS code in a function and call the function once the DOM has loaded, or just put your JS code at the end of your page, right before </body>.


Post a Comment for "Javascript - Get A Date From An HTML Input"