2013-04-05 61 views
1

我在Rails應用程序中使用jQuery來顯示來自助手(我沒有使用Datepicker)的開始時間和結束時間。選擇大於start_time的end_time

在我的形式:

.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}") 

的時間列表來自幫手(即start_timeend_time)。我如何驗證時間,以便我只能選擇比start_time大的end_time

回答

1

您可以禁用選項http://www.w3schools.com/tags/att_option_disabled.asp

我會使用JavaScript來運行「end_time」數組選擇選項並禁用任何小於「start_time」的選項。

像這樣的東西(id和東西將需要進行修改):

$("#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'); 
     } 
    }); 
)}; 
+0

嘿亞歷克斯感謝您的快速和幫助充分反應。另一個問題是,我如何禁用結束時間,因爲它來自Arrary,如[ ['12:00 AM'], ['12:30 AM'], ['1:00 AM']] – 2013-04-05 07:11:44

+0

I 'd解析字符串並將其變爲24小時無AM或冒號的時間。 IE:「12:30 AM」爲030,「9:00 AM」爲900.「5:00 PM」爲1700.這些數字很容易比較。這可能有助於解析http://stackoverflow.com/questions/9640266/convert-hhmmss-string-to-seconds-only-in-javascript – 2013-04-05 07:19:41

+0

亞歷克斯,它不適用於我..當我使用此代碼,它只會在保存後禁用字段(在編輯的情況下,它會禁用字段),但我希望在選擇開始時間的同時提供該功能。請給點建議! – 2013-04-05 11:21:08