简体   繁体   中英

Disable option when clicked in select

How do I make disable an option when a select is clicked? Here is my code, which does not work. There are no errors in the console.

Here it is:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
        window.onload = function () {
            var numSelect = document.getElementsByClassName("numSelector");
            for (var i = 0; i < numSelect.length; i++) {
                numSelect[i].innerHTML="<span class='firstSelector'><option>Select Number</option></span><option>1/2</option>";
                numSelect[i].onclick = disableSelect;

            }
        }
        function disableSelect() {
            for (var a = 0; a < document.getElementsByClassName("firstSelector").length; a++) {
                document.getElementsByClassName("firstSelector")[i].innerHTML="<optgroup>Select Number</optgroup>";
            }

        }
        </script>
    </head>

    <body>
        <select class="numSelector"></select>
        <select class="numSelector"></select>
    </body>
</html>

Just use pure HTML

 <select required> <option value="" selected disabled>Select Number</option> <option>1</option> <option>etc..</option> </select> 

You could also add the hidden attribute if you don't want it to show up in the dropdown too (at the moment it is visible but disabled)

The required attribute on the <select> means that not choosing a number will prevent submission (though you should still validate serverside)

I'm not sure what you want but here is the ways to disabled dropdown value.

<select id="select1" onclick="disableSelectedItem(this);">
    <option>Select Number</option>
    <option>1</option>
    <option>2</option>
</select>

<select id="select2" onclick="disableFirstItemOnly(this);">
    <option>Select Number</option>
    <option>1</option>
    <option>2</option>
</select>

<script type="text/javascript">
    function disableSelectedItem(ddl) {
        var value = ddl.options[ddl.selectedIndex].value;
        var count = ddl.length;

        for (var i = 0; i < count; i++) {
            if (ddl.options[i].value == value) 
                ddl.options[i].disabled = true;
            else 
                ddl.options[i].disabled = false;
       }
     }

     function disableFirstItemOnly(ddl) {
         ddl.options[0].disabled = true;
     }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM