使用javascript在第一个选择列表选项的基础上更改第二个选择列表

Use javascript to change second select list based on first select list option

本文关键字:选择 列表 基础上 第二个 选项 第一个 javascript 使用      更新时间:2023-09-26

我有两个下拉列表,它们由存储在数据库中的相同日期数组填充。我想使用javascript或jquery根据第一个列表中的选择更改第二个下拉列表。因此,一个例子是,如果用户在第一个开始日期列表中选择2012年3月3日,那么我希望第二个列表只显示或允许数组中的未来日期。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);
});

这里有一些不同的解决方案,包括服务器端。这是一种常见的情况,我相信如果你搜索得更多,你可以在这个网站上找到更多的例子。

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

使用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
        }
    });
});

});

我没有测试过,但有点像