Completing a Simple Date Picker with JavaScript and CSS - Focusing on Visitor Selections
(Page 2 of 4 )
Now we need to focus on getting the visitor's selections into the text field in the form. We should only do this once an entire date has been selected, so since we already know that the day part of the date will be selected last, we can use the existing getDay() function for this purpose as well. The first thing we should do however, is make the month variable appear as a number instead of letters. We can easily change the selected month into its numerical equivalent using an array of the months and a little For loop to good effect:
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
for (x = 0; x < months.length; x++) {
if (months[x] == month) {
month = x + 1;
}
}
We first hard code the array values, then set a for loop to iterate through each month in the array. On each cycle, the code will execute the if statement that looks for a match between the current array item and the value of our month variable. When the match is found, the script changes the value of our variable to the current value of x. We have to add 1 to the number held in the x variable because the array, and therefore x, start at zero.
To tidy the month up further, we can add some code that will make the month two digits for any month. Just below the line of code that reads month = x + 1 add:
if (month<= 9) {
month = "0" + month.toString();
}
We could probably come up with a part of the function that changes a day that is less than 9 to a two digit string as well, but the easiest thing to do is to go back to the HTML file and add a zero to the front of the first nine day elements. Next, we can concatenate our variables to create one master string:
var datestring = day + "/" + month + "/" + year;
Next: Adding the datestring >>
More JavaScript Articles
More By Dan Wellman