jQuery: changing the available options in a list based on the selected option
<select id="studentinst" size="6">
<option value="1">First Installment</option>
<option value="2">Second Installment</optio开发者_JAVA技巧n>
<option value="3">Third Installment</option>
<option value="4">Fourth Installment</option>
<option value="5">Fifth Installment</option>
<option value="6">Sixth Installment</option>
</select>
If I select 4, it should only display the first 4 options and the rest should be hidden. Desired output:
First Installment
Second Installment
Third Installment
Fourth Installment
How can I achieve this using jQuery?
see sample link check this link... for loop doesn't work over here
$('#studentinst').change(function() {
if ($('option:selected').val() == 4) {
$("#studentinst option[value=5]").remove();
$("#studentinst option[value=6]").remove();
}
else {
if ($('#studentinst option[value=5]').val() == null)
$('<option>').text('Fifth Installment').val(5).appendTo($('#studentinst'));
if ($('#studentinst option[value=6]').val() == null) $('<option>').text('Sixth Installment').val(6).appendTo($('#studentinst'));
}
});
If hide doesn't work as expected, this is another way to do it.
see sample
Something like this should work, there may be a shorter way to do it?
$(document).ready(function(){
$('#studentinst').change(function(){
var selectedIndex = $('#studentinst :selected').index();
$('#studentinst option').each(function(){
if($(this).index() > selectedIndex){
$(this).hide(); //or you can use .remove();
}
});
});
});
This method is based on the options index but you could use .val() instead if .index() if you are basing the removal on the values
精彩评论