How to limit options in a <select> based on another option selection

前端 未结 3 1636
盖世英雄少女心
盖世英雄少女心 2021-01-16 09:29

I\'m trying to limit the number of options based on another selection. For instance in this example \"How many credits is the class you skipped?\" should be limited to equal

3条回答
  •  时光说笑
    2021-01-16 09:46

    I've created a quick function to help you out, there may be a neater way to do this, but it does the job quite nicely!

    Onchange of the element #semester_credits I grab the value (number of semesters credits and then loop over the next select box and remove the ones that have a higher value that the chosen one, I use a global var to cache the removed options in case the user changes their minds and we need to add them back in.

    $(function () {
    
    var savedOpts = "";
    $('#semester_credits').change(function() {
        //Add all options back in;
        if( savedOpts ) {
            $('#skipped_total_credits').append(savedOpts);
            savedOpts = "";
        }
    
        //Return false if blank option chosen;
        if( $(this).val() === "0" )
            return false;
    
        var chosenCreds = parseInt($(this).val());
        $('#skipped_total_credits option').each(function() {
            var thisCred = parseInt($(this).val());
            if(thisCred > chosenCreds) { 
                //Remove
                savedOpts += $(this)[0].outerHTML;
                $(this).remove();
            }
        });
    });
    

    Here an updated fiddle

    p.s the example Kai Hartmann suggests is also a nice way to achieve this.

提交回复
热议问题