Refining a Simple Date Picker with JavaScript and CSS
(Page 1 of 4 )
In part one of this series, we looked at the HTML and CSS needed to construct the date-picker popup and style it accordingly. In this part, we are going to write the JavaScript that is going to make it work. This is going to be accomplished with a mixture of plain JavaScript with some DOM retrieval and manipulation.
All you'll need for this article is the source code from the first article and a simple text editor. In this text editor, add the first of the functions that we need: the function that allows the date picker to be opened. As the calendar has been hidden from display initially with CSS, we can adjust this rule dynamically using the DOM to alter the required element:
function showPicker() {
document.getElementById("picker").style.display = "block";
}
Don't forget to go back to the datepicker.htm file and add id="picker" to the picker div, and an onclick="showPicker();" call to the calendar image. You'll also need to link the newly created JavaScript file to the HTML file with something along the lines of
<script type="text/javascript" src="datepicker.js">
</script>
Next we need to get the date selected by the visitor and put it in the form field. There are essentially three elements to capture so we can start off by defining three empty variables:
var day = "";
var month = "";
var year = "";
We'll skip the function that gets the day for now and move on to the function that gets the month selected by the visitor:
function getMonth() {
var option = document.getElementById("month").selectedIndex;
month = document.getElementById("month").options[option].text;
}
First we get the option that has been chosen in the select box, and then we get the value of the text inside the selected option. The function that gets the selected year is equally as simple:
function getYear() {
var option = document.getElementById("year").selectedIndex;
month = document.getElementById("year").options[option].text;
}
Everything is the same except the id of the select box. You'll also need to go back to the HTML file and add the required ID and onchange attributes to the two select objects. Now we can go back to getting the selected day element.
Next: Getting the day element >>
More JavaScript Articles
More By Dan Wellman