![](/img/trans.png)
[英]Use javascript to change a second select list based on the first select list option?
[英]Use javascript to change second select list based on first select list option
我有兩個下拉列表,這些列表是從存儲在數據庫中的相同日期數組中填充的。 我想使用javascript或jquery根據第一個列表中的選擇更改第二個下拉列表。 例如,如果用戶在第一個開始日期列表中選擇03/03/2012,那么我希望第二個列表僅顯示或允許數組中的未來日期。 3 / 3,3 / 2和3/1將顯示為灰色或被移除,3 / 4,3 / 5將保留為可選選項。 任何人都可以幫助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>
使用您的實際示例,如果兩個列表完全相同,那么如果您使用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);
});
這里有一些不同的解決方案,包括服務器端。 這是一種常見的情況,如果您再搜索一下,我相信您可以在此網站上找到更多示例。
使用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
}
});
});
});
我沒有測試,但是就是這樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.