Reputation: 293
I have two select boxes starting year and ending year. it is possible using javascript or jquery where when i select 2016 for starting year.. i will only see 2017 and 2018 in the ending year select box ?
<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>
Upvotes: 0
Views: 75
Reputation: 1360
You have to implement two methods for hiding option list:
Example:
$( '#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>
Upvotes: 1