I'm trying to get a date directly from an HTML calendar input, with a simple console log (for testing purposes), without the need for a button.
I've tried a few variations of the code below:
<div class = "Comparisons_Wrapper">
<input type="date" class="DateSelector" id = "DateSelector" onclick="getDate()">
</div>
<script>
function getDate(){
var date = document.getElementById("DateSelector").value;
console.log(date)
}
</script>
I was hoping the onclick part of the div, would call the function on clicking the date from the calendar, but instead calls the function on immediately clicking the input box to open up the calendar, so you initially get an empty console.log the first time, and then when you click on the box again, you get the date you initially entered. I guess this assumption was naïve of me.
Any assistance would be appreciated,
Thanks James
What you want to do in this case is to add an event listener to the input's change event.
var dateInput = document.getElementById("DateSelector");
dateInput.addEventListener('change', function(event) {
console.log(event.target.value)
});
<div class = "Comparisons_Wrapper">
<input type="date" class="DateSelector" id = "DateSelector">
</div>
Use events like onchange, as follow:
function handler(e){
alert(e.target.value);
}
<input type="date" class="DateSelector" id="DateSelector" onchange="handler(event);">