1

I'm using jQuery in a Rails app to show the start time and end time, which come from helper (I'm not using Datepicker).

In my form:

 .field
     = f.label :start_time
     = f.select :start_time, options_for_select( [""] + start_time, "#{f.object.start_time.strip}")       
    .span#end_time
      .field
        = f.label :end_time
        = f.select :end_time, options_for_select( [""] + end_time, "#{f.object.end_time.strip}")

The time list comes from helper (i.e. start_time and end_time). How can I validate the time so that I can only select an end_time that is greater than the start_time?

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
Rajeev Thakur
  • 109
  • 11

1 Answers1

1

You can disable options http://www.w3schools.com/tags/att_option_disabled.asp.

I'd use javascript to run through the array of "end_time" select options and disable any that are less than "start_time".

Something like this (id's and stuff will need to be modified):

$("#start_time").change(function() {
    // Get start time
    var start_time = $("#start_time").find(":selected").text();

    // Iterate through end time options
    $("#end_time option").each(function() {
        var end_time = $(this).text();
        // Depending on how end_time and start_time are formatted you may need to do some conversion here
        if (start_time > end_time) {
            $(this).attr('disabled','disabled');
        }
    });
)};
Alex Marchant
  • 2,490
  • 27
  • 49
  • Hey Alex Thanks for your quick and help full response. One another question is that how I disable end time as it comes from an Arrary like [ ['12:00 AM'], ['12:30 AM'], ['1:00 AM'] ] – Rajeev Thakur Apr 05 '13 at 07:11
  • I'd parse the string and turn it into 24 hour time without AM or the colon. IE: "12:30 AM" would be 030, "9:00 AM" would be 900. "5:00 PM" would be 1700. These numbers would be easily comparable. This might help with the parsing http://stackoverflow.com/questions/9640266/convert-hhmmss-string-to-seconds-only-in-javascript – Alex Marchant Apr 05 '13 at 07:19
  • Alex, It doesn't work for me..when I use this code, it only disable fields after save( in edit case, it disable the fields), but I want that functionality while I select the start time. Please give some suggestion ! – Rajeev Thakur Apr 05 '13 at 11:21
  • You'll have to run this entire bit of code every time the #start_time select field is changed. I've edited the above code to show that. – Alex Marchant Apr 05 '13 at 22:34