Last active
December 18, 2015 22:29
-
-
Save pfgray/5854551 to your computer and use it in GitHub Desktop.
turn input boxes into super-usable time inputs!
This file contains 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
SmartTime = function(options){ | |
var textBoxes = $(options.inputs); | |
if(options.onerror && typeof(options.onerror) != 'function'){ | |
console.error('Error: onerror is not a function'); | |
return; | |
} | |
var fixTime = function(input){ | |
var hour; | |
var minute; | |
if(input.length < 3){//this means that the user is inputting hours | |
minute = "00"; | |
hour = input; | |
if(checkHour(hour)){ //hour is bad | |
return { | |
error:true, | |
text:input | |
}; | |
} | |
} | |
else if(input.indexOf(":",0) == -1){ //this means that the user did not enter a ":" | |
minute = input % 100; | |
hour = Math.floor(input / 100); | |
if(checkHour(hour) || checkMinute(minute)){ | |
return { | |
error:true, | |
text:input | |
}; | |
} | |
} | |
else{//user inputted a ":" | |
minute = input.substring(input.indexOf(":")+1, input.indexOf(":")+3); | |
hour = input.substring(0, input.indexOf(":")); | |
if(checkHour(hour) || checkMinute(minute)){ | |
return { | |
error:true, | |
text:input | |
}; | |
} | |
} | |
minute+=''; | |
if(minute.length < 2){ | |
minute = "0"+minute; | |
} | |
return { | |
error:false, | |
text:hour + ":" + minute | |
}; | |
} | |
var checkHour = function(hour){ | |
var highHourLimit = (options.format && options.format == '24') ? 24 : 12; | |
if(isNaN(hour) || hour < 1 || hour > highHourLimit){ | |
//TODO: throw error | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
var checkMinute = function(minute){ | |
if(isNaN(minute) || minute < 0 || minute > 59){ | |
//TODO: throw error | |
return true; | |
}else{ | |
return false; | |
} | |
} | |
$.each(textBoxes, function(index, value){ | |
var textBox = $(value); | |
if(!textBox || !textBox.is('input') || !textBox.attr('type') == 'text'){ | |
console.error('Error: element #'+index + '; ' + textBox + ' is not a valid input text element' ); | |
}else{ | |
//set it up! | |
textBox.focus(function(){ | |
textBox.select(); | |
}); | |
textBox.blur(function(){ | |
var result = fixTime(textBox.val()); | |
textBox.val(result.text); | |
if(!result.error){ | |
if(options.onsuccess){ | |
options.onsuccess(textBox); | |
} | |
}else{ | |
if(options.onerror){ | |
options.onerror(textBox, 'error'); | |
} | |
} | |
}); | |
textBox.mouseup(function(e){ | |
e.preventDefault(); | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
*note: requires jQuery