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

前端 未结 3 1648
盖世英雄少女心
盖世英雄少女心 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:45

    If you want the drop-down list for a question to change based on previous answer, you need to add an onchange event to each select element which would update another drop-down. This should then call a function which removes or adds elements in your form.

    Otherwise, you can add a validation function for your Calculate button.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-16 10:00

    On change of your dropdown fire a onchange trigger and on the basis of values make the 2nd dropdown enable or disabled.

    $("#semester_credits").change(function () {
            var $this=this;
            $("#skipped_total_credits").children().each(function(){
                $(this).attr("disabled",parseInt($this.value) < parseInt(this.value));
            });
        });
    

    Check the fiddle here

    EDIT

    $this.value contains the value selected from "semester_credits" dropdown, now For each child of "skipped_total_credits", I am checking if that value is less than the children value then make it disabled, i.e attr("disabled", true) else make that children enabled.

    0 讨论(0)
提交回复
热议问题