依赖选择框开始年份和结束年份

时间:2018-05-27 15:50:02

标签: javascript jquery

我有两个选择框开始年份和结束年份。  有可能使用javascript或jquery,当我选择2016年开始年份时..我只会在结束年份选择框中看到2017年和2018年?

<select id='starting_year'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
<option value='2017'>2017</option>
<option value='2018'>2018</option>
</select>
<select id='ending_year'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
<option value='2017'>2017</option>
<option value='2018'>2018</option>
</select>​

1 个答案:

答案 0 :(得分:1)

您必须实现两种隐藏选项列表的方法:

  1. display:none;适用于FF,但不适用于Chrome或IE。
  2. 您可以将元素附加到隐藏元素。
  3. 示例:

    $( '#starting_year' ).on( 'change', function() {
        var startYear = $( this ).children( ':selected' ).val();
    
        $( '#hidden_end' ).children().appendTo( '#ending_year' );
    
        $( '#ending_year option' ).each( function() {
            if ( $( this ).val() < startYear ) $( this ).appendTo( '#hidden_end' )
        } )
    
        var options = $( '#ending_year option' ).sort( function ( a, b ) {
            return ( a.value > b.value ) ? 1 : -1
        } );
    
        options.appendTo( $( '#ending_year' ) );
        $( '#ending_year option:selected' ).removeAttr( 'selected' );
        $( '#ending_year option:first-child' ).attr( 'selected', 'selected' )
    } )
    
    $( '#ending_year' ).on( 'change', function() {
        var endYear = $( this ).children( ':selected' ).val();
    
        $( '#hidden_start' ).children().appendTo( '#starting_year' );
    
        $( '#starting_year option' ).each( function() {
            if ( $( this ).val() > endYear ) $( this ).appendTo( '#hidden_start' )
        } )
    
        var options = $( '#starting_year option' ).sort( function ( a, b ) {
            return ( a.value > b.value ) ? 1 : -1
        } );
    
        options.appendTo( $( '#starting_year' ) );
        $( '#starting_year option:selected' ).removeAttr( 'selected' );
        $( '#starting_year option:first-child' ).attr( 'selected', 'selected' )
    } )
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>
        <label for="starting_year">Starting Year:</label>
        <select id='starting_year'>
            <option value='2015'>2015</option>
            <option value='2016'>2016</option>
            <option value='2017'>2017</option>
            <option value='2018'>2018</option>
        </select>
    </div>
    <br>
    <div>
        <label for="ending_year">Ending Year:</label>
        <select id='ending_year'>
            <option value='2015'>2015</option>
            <option value='2016'>2016</option>
            <option value='2017'>2017</option>
            <option value='2018'>2018</option>
        </select>
    </div>
    
    <div id="hidden_end" style="display: none"></div>
    <div id="hidden_start" style="display: none"></div>