Manoz Manoz - 1 month ago 6
Javascript Question

Select larger value from dropdown

I have a dropdown with the lists of times.

My condition is-

select only option whose value is just greater than current time


However, I have implemented the way i could do it and this is working fine but there must be a better way of doing this, I am afraid that my implementation may break in some certain conditions.

Here is what I have done-

HTML-

<select name="RunID" id="RunID" >
<option>Select Departure Time...</option>
<option value="09:00:00">09:00</option>
<option value="12:30:00" >12:30</option>
<option value="15:30:00">15:30</option>
<option value="18:30:00">18:30</option>
<option value="22:30:00">22:30</option>
<option value="01:30:00">01:30</option>
</select>


jQuery

var arrayTimes = [];

$('#RunID option').not(':first-child').each(function () {

var timeNow = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

if (Date.parse('01/01/2011 ' + $(this).val())
> Date.parse('01/01/2011 ' + timeNow)) {

arrayTimes.push($(this));
}
});

if (arrayTimes.length > 0) {
arrayTimes[0].attr('selected', 'selected');
}


and the Demo

Edit-

May be this question is creating confusion so I simply put an example for this.
As in my dropdown there are times
09:00:00
,
12:30:00
,
15:30:00
...

Now the current time is 12:58:25 seconds.

so accordingly the default selected value would be
15:30:00
because this is most nearly greater value than this current time.

Also, I am not trying to disable any of values which doesn't match with the condition!

K K K K
Answer

Try this:

JS:

var D = new Date();
var T = D.getTime();
var options = $('#RunID option[data-departuretime]');
var op = options.filter(function (el) {
    var d = new Date(D.getFullYear() + " " + (D.getMonth() + 1) + " " + D.getDate() + " " + $(options[el]).attr("data-departuretime"));
    return d.getTime() > T;
});
$(op[0]).attr("selected", "selected");

HTML:

<select name="RunID" id="RunID">
    <option>Select Departure Time...</option>
    <option data-departuretime="09:00:00">09:00</option>
    <option data-departuretime="13:35:10">13:35:10</option>
    <option data-departuretime="15:30:00">15:30</option>
    <option data-departuretime="18:30:00">18:30</option>
    <option data-departuretime="22:30:00">22:30</option>
    <option data-departuretime="01:30:00">01:30</option>
</select>

Demo: http://jsfiddle.net/m39eodde/2/

Comments