How to style Disabled Options in a form

后端 未结 8 1640
不思量自难忘°
不思量自难忘° 2020-12-10 10:39

I\'m using a form with a drop-down menu that contains some options disabled, so the users cannot select them. I\'m trying to customize via css these elements but I have some

相关标签:
8条回答
  • 2020-12-10 11:27
    var select = document.getElementsByTagName("select");
    
    for(var i = 0;i < select.length; i++)
    {
    var el = select[i];
    var optVal = el.options[el.selectedIndex].value
    el.addEventListener('change', function () {
    // Using an if statement to check the class
        if (optVal == "") {
            el.classList.remove('not_chosen');
        } else {
            el.classList.add('not_chosen');
        }
    });
    }
    
    0 讨论(0)
  • 2020-12-10 11:31

    I used a simple hack to make disabled options grey, hopefully someone finds it useful.

    <label>
        <div id="disabledMask"></div>
        <select id="mySelect">
            <option disabled selected>Please Select</option>
            <option value="foo">Bar</option>
        </select>
    </label>
    
    <style>
        label {
            position: relative;
        }
    
        #disabledMask {
            position: absolute;
            background-color: #fff;
            opacity: 0.5;
            pointer-events: none;
            width: 100%;
            height: 100%;
            display: none;
        }
    </style>
    
    <script>
        var toggleMask = function(){
            var option = this.options[this.selectedIndex];
            var disabledMask = document.getElementById('disabledMask');
            disabledMask.style.display = option.disabled? 'block' : 'none';
        };
    
        var mySelect = document.getElementById('mySelect');
        mySelect.addEventListener('change', toggleMask);
        toggleMask.bind(mySelect)();
    </script>
    

    Here is a jsfiddle: https://jsfiddle.net/jhavbzcx/

    Disclaimer: depending on the styling of your select you may need to style the #disabledMask so as not to overlap the dropdown arrow.

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