我有两个选择框开始年份和结束年份。 有可能使用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>
答案 0 :(得分:1)
您必须实现两种隐藏选项列表的方法:
示例:强>
$( '#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>