开发者

jQuery: changing the available options in a list based on the selected option

开发者 https://www.devze.com 2023-04-09 10:49 出处:网络
<select id=\"studentinst\" size=\"6\"> <option value=\"1\">First Installment</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

0

精彩评论

暂无评论...
验证码 换一张
取 消