Prevent Multiple Selections of Same Value

后端 未结 7 757
渐次进展
渐次进展 2020-12-09 06:36

I am working on a project where I have a form that will have multiple \'select\' inputs, all with the same set of options. I would like to use jquery to disable/hide an opt

7条回答
  •  忘掉有多难
    2020-12-09 07:19

    This question was the top google result for searching for an answer to this, so I'll post an updated answer here. This is almost the exact same as netadictos's answer, but works for disabling and re-enabling the select values and uses prop instead of attr. Verified working in Chrome 52.

        $("select").change(function()
        {
            $("select option").prop("disabled",""); //enable everything
    
            //collect the values from selected;
            var  arr = $.map
            (
                $("select option:selected"), function(n)
                {
                    return n.value;
                }
            );
    
            //disable elements
            $("select option").filter(function()
            {
                return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
            }).prop("disabled","disabled");
    
            //re-enable elements
            $("select option").filter(function()
            {
                return $.inArray($(this).val(),arr)==-1; //if value is not in the array of selected values
            }).prop("disabled","");
        }).trigger("change"); // Trigger the change function on page load. Useful if select values are pre-selected.
    

提交回复
热议问题