Question

I need to user to select a time, and the slider seems the best option for this, however, it is only made for decimal values. This should not be a problem because I can thread them as 'minutes since 0:00', but I need to override what is displayed to the user in the inputbox and tooltip.

Is there a way to override the decimal values with custom formatting, so I convert 'minutes since 0:00' to a readable time (like 8:30)?

Was it helpful?

Solution

The jQM slider uses type="number" and also hooks up the input to its code. So one way around this is to hide the input, get its value, convert to the string you want and write to your own input placed where the old one was.

DEMO

I have placed the slider markup within a named container and added an input to the container that will display the time:

<div id="theTime" class="time-slider">
    <label for="sliderTime">Time:</label>
    <input type="range" name="sliderTime" id="sliderTime" data-highlight="true" min="0" max="1444" value="60" />
    <input type="text" data-role="none" class="timeLabel ui-shadow-inset ui-body-inherit ui-corner-all ui-slider-input" value="1:00" disabled />
</div>

In CSS, I hide the existing input and then place the new input where the old one was:

.time-slider input[type=number] {
    display: none; 
}
.time-slider .timeLabel{
    position: relative;
    top: -38px;
}

Then in code, handle the change event, convert minutes to time string and write the string to the new INPUT and the tooltip of the slider handle:

$(document).on("pagecreate", "#page1", function(){       
    $("#sliderTime").on("change", function(){
        var time = IntToTime($(this).val());
        $("#theTime .timeLabel").val(time);
        $("#theTime .ui-slider-handle").prop("title", time);
    });    
});

function IntToTime(val){
    var hours = parseInt( val / 60 );
    var min = val - (hours * 60);
    var time = hours + ':' + (min < 10 ? '0' + min : min);
    return time;
}

UPDATE: There was some interest in doing this with a range slider in order to select a start and end time. I have created an updated fiddle with a solution:

RANGESLIDER FIDDLE

OTHER TIPS

If you need a single slider then check the following code based on JQuery UI Slider for time

$(function() {
$("#slider-range").slider({       
    min: 0,
    max: 1440,
    step: 15,
    slide: function(e, ui) {
        var hours = Math.floor(ui.value / 60);
        var minutes = ui.value - (hours * 60);

        if(hours.length == 1) hours = '0' + hours;
        if(minutes.length == 1) minutes = '0' + minutes;
        if(minutes==0)minutes = '00';
        $('#slider1Value').html(hours+':'+minutes);
    }
});
});

Fiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top