Date selects from text input
Quick hack for creating date select boxes from a date of birth text input. Accepts date value as YYYY-MM-DD or DD/MM/YYYY
by akbsteam
HTML
<input type="text" class="dob" name="dob" value="1991-04-12" />
JavaScript
$.fn.dob = function( type ) {
return this.each(function() {
var $this = $(this),
strpad = function(number, length) {
var str = number.toString();
while (str.length < length) {
str = '0' + str;
}
return str;
},
wrapper = $('<div></div>'),
day = $('<select></select>'),
month = $('<select></select>'),
year = $('<select></select>'),
i=0,
topts = '',
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
cYear = (new Date()).getFullYear(),
s = '',
initial = $this.val(),
spl;
if(initial.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)) {
spl = initial.split('-');
} else if(initial.match(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/)) {
spl = initial.split('/').reverse();
} else {
spl = ["1985", "01", "01"];
}
topts = '';
for(i=1; i<32; i+=1)
{
s = (i == parseInt(spl[2], 10)) ? ' selected="selected"' : '';
topts += '<option value="'+strpad(i, 2)+'"'+s+'>'+i+'</option>';
}
day.html(topts);
topts = '';
for(i=1; i<13; i+=1)
{
s = (i == parseInt(spl[1], 10)) ? ' selected="selected"' : '';
topts += '<option value="'+strpad(i, 2)+'"'+s+'>'+months[i-1]+'</option>';
}
month.html(topts);
topts = '';
for(i=cYear-100; i<=cYear; i+=1)
{
s = (i == parseInt(spl[0], 10)) ? ' selected="selected"' : '';
topts += '<option...