2012-03-16 151 views
1

我有兩個下拉列表填充從數據庫中存儲的相同日期的數組。我想使用JavaScript或jQuery來更改第二個下拉列表,其基於第一個列表中的選擇。因此,例如,如果用戶在第一個開始日期列表中選擇了03/03/2012,那麼我希望第二個列表僅顯示或允許數組中的未來日期。 3/3,3/2和3/1會變灰或去除,3/4,3/5將作爲可選選項保留。任何人都可以幫助JavaScript編碼或提出另一個建議?使用javascript更改第二個選擇列表基於第一個選擇列表選項

<select id='start_date' name='data[sDate]' title='Use the drop list'> 
<option value="" selected="selected"> </option> 
<option value="03/05/2012">03/05/2012</option> 
<option value="03/04/2012">03/04/2012</option> 
<option value="03/03/2012">03/03/2012</option> 
<option value="03/02/2012">03/02/2012</option> 
<option value="03/01/2012">03/01/2012</option> 
</select> 

<select id='end_date' name='data[eDate]' title='Use the drop list'> 
<option value="" selected="selected"> </option> 
<option value="03/05/2012">03/05/2012</option> 
<option value="03/04/2012">03/04/2012</option> 
<option value="03/03/2012">03/03/2012</option> 
<option value="03/02/2012">03/02/2012</option> 
<option value="03/01/2012">03/01/2012</option> 
</select> 
+0

您是否也使用服務器端語言? – Panagiotis 2012-03-16 21:12:51

+0

好點,這對於服務器端來說會容易得多。 – mikevoermans 2012-03-16 21:15:05

回答

3

與您實際的例子,如果兩個列表是完全一樣的,然後如果你用index()工作,它很簡單。看http://jsfiddle.net/elclanrs/7YrqY/

$('#start_date').change(function(){ 
    var $selected = $(this).find('option:selected'); 
    $('#end_date') 
     .find('option') 
     .prop('disabled', false) 
     .eq($selected.index()-1) 
     .nextAll() 
     .prop('disabled', true); 
}); 
+0

+1漂亮和優雅 – 2012-03-16 21:26:33

+0

+1在jsfiddle中很好用,看起來像是我需要的,但是我的實現失敗了。是否有任何其他組件/資源需要引用?我目前正在引用ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js「 – sloga 2012-03-16 22:48:57

0

這裏有幾個不同的解決方案,包括服務器端。這是一種常見的情況,如果你多搜索一下,我相信你可以在這個網站上找到更多的例子。

http://css-tricks.com/dynamic-dropdowns/

+0

該網站更多地是從各種外部來源獲得第二個下拉列表元素,但它的工作原理。 – gereeter 2012-03-16 21:38:46

0

使用jQuery

$(function(){ //when the page is loaded 

$("#start_date").change(function(){ //register a anonymous function that will be called when the element with id=start_date changes his values 

    var start = $(this).val(); //gets the value of the element 

    $("#end_date option").each(function(i){//for each option of end_date 

     if(new Date($(this).val()).getTime() < new Date(start).getTime()){ //if the date of the element is before the start 
      $(this).hide(); //hide the element 
     }else{ 
      $(this).show(); //shows the element 
     } 
    }); 

}); 

});

我沒有測試,但是是這樣的東西

相關問題