Skip to content

Instantly share code, notes, and snippets.

@sebastianhomeier
Created November 28, 2015 16:32
Show Gist options
  • Save sebastianhomeier/7c0a9165ac60df67abea to your computer and use it in GitHub Desktop.
Save sebastianhomeier/7c0a9165ac60df67abea to your computer and use it in GitHub Desktop.
Time (hh:mm:ss) input with number input elements
<div class="input-time-wrapper">
<input id="hour" class="input-time input-time__hour" type="number" value="00" min="-1" max="24" />
:<input id="min" class="input-time input-time__min" type="number" value="00" min="-1" max="60" />
:<input id="sec" class="input-time input-time__sec" type="number" value="00" min="-1" max="60" />
</div>
var $hourInput = $('#hour'),
$minInput = $('#min'),
$secInput = $('#sec');
$hourInput.on('input', onHourChange);
$minInput.on('input', onMinChange);
$secInput.on('input', onSecChange);
function onHourChange(e) {
setHour($hourInput.val());
}
function onMinChange(e) {
setMin($minInput.val());
}
function onSecChange(e) {
setSec($secInput.val());
}
function setHour(value, forceSetValue) {
if(0 === value.length) {
$hourInput.val('00');
}else if(1 === value.length) {
$hourInput.val('0' + value);
}else if(value.length > 2) {
$hourInput.val(value.slice(0, 2));
}else if('24' === value) {
$hourInput.val('00');
}else if('-1' === value) {
$hourInput.val('23');
}else if(forceSetValue) {
$hourInput.val(value);
}
}
function setMin(value, forceSetValue) {
if(0 === value.length) {
$minInput.val('00');
}else if(1 === value.length) {
$minInput.val('0' + value);
}else if(value.length > 2) {
$minInput.val(value.slice(0, 2));
}else if('60' === value) {
$minInput.val('00');
setHour('' + (parseInt($hourInput.val()) + 1), true);
}else if('-1' === value) {
$minInput.val('59');
setHour('' + (parseInt($hourInput.val()) - 1), true);
}else if(forceSetValue) {
$minInput.val(value);
}
}
function setSec(value, forceSetValue) {
if(0 === value.length) {
$secInput.val('00');
}else if(1 === value.length) {
$secInput.val('0' + value);
}else if(value.length > 2) {
$secInput.val(value.slice(0, 2));
}else if('60' === value) {
$secInput.val('00');
setMin('' + (parseInt($minInput.val()) + 1), true);
}else if('-1' === value) {
$secInput.val('59');
setMin('' + (parseInt($minInput.val()) - 1), true);
}else if(forceSetValue) {
$secInput.val(value);
}
}
.input-time-wrapper {
border: 1px solid #ccc;
display: inline-block;
.input-time {
border: none;
font-size: 0.875em;
margin: 0;
padding: 5px 0 5px 20px;
width: 32px;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment