Created
October 5, 2015 23:57
-
-
Save hellozach/40ae9d5207a7aa8f733a to your computer and use it in GitHub Desktop.
Adds a polyfill for browsers that do not support time inputs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.timepicker = function() { | |
return this.each(function() { | |
var self = $(this), | |
rqrd = self.prop('required'), | |
poly = $('<div class="form-inline polyfill-time" />'), | |
hour = $('<input type="number" class="form-control" size="2" maxlength="2" placeholder="12">'), | |
mins = $('<input type="number" class="form-control" size="2" maxlength="2" placeholder="00">'), | |
ampm = $('<select class="form-control"><option value="am">AM</option><option value="pm">PM</option></select>'), | |
time = { | |
hour: 0, | |
mins: 0, | |
ampm: 'am', | |
}; | |
function updateTime() { | |
time.hour = time.hour > 12 ? time.hour - 12 : time.hour; | |
time.mins = time.mins < 10 ? '0' + time.mins : time.mins; | |
if( time.ampm == 'am' && time.hour < 13 ) { | |
var value = ( time.hour == 12 ? '00' : time.hour ) + ':' + time.mins; | |
} else { | |
var value = ( ( time.hour == 12 ? '12' : time.hour - -12 ) ) + ':' + time.mins; | |
} | |
self.val(value); | |
console.log(time.ampm); | |
} | |
poly.append(hour).append(' : ').append(mins).append(' ').append(ampm); | |
self.after(poly); | |
self.attr('type', 'hidden'); | |
hour.on('keyup', function() { | |
time.hour = $(this).val(); | |
updateTime(); | |
}); | |
mins.on('keyup', function() { | |
time.mins = $(this).val(); | |
updateTime(); | |
}); | |
ampm.on('change', function() { | |
time.ampm = $(this).val(); | |
updateTime(); | |
}); | |
if( rqrd ) { | |
hour.prop('required', true); | |
mins.prop('required', true); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment