How to get dates and numbers from an HTML input
Introduction
I still remember the days when there were no specialized <input> tags. You had the generic <input type="text">, <input type="button">, <input type="file">, <input type="hidden"> and some other. But basically, the validations were done via JavaScript in an <input type="text">.
For some time now we have had many other specialized such as <input type="color"> to make a color picker appear, <input type="date"> to display a calendar, <input type="number"> to increment or decrement numbers, etc.
And it is just about these last two (date and number), of which we are going to comment on a small functionality that you may not know about.
Getting the value of the field
To access the value of the <input>, just access the inputElement.value property. It returns the current value as a string. If the value has not yet been specified, it also returns a string, in this case empty ('').
function extractValue(element) {
// We return the property "value"
return element.value
}
/* Demo code */
function updateElements() {
const date = extractValue(document.getElementById('date-input'))
document.getElementById('date-value').textContent = date
document.getElementById('date-type').textContent = typeof date
const number = extractValue(document.getElementById('number-input'))
document.getElementById('number-value').textContent = number
document.getElementById('number-type').textContent = typeof number
}
updateElements()
document
.getElementById('date-input')
.addEventListener('change', updateElements)
document
.getElementById('number-input')
.addEventListener('change', updateElements)