Skip to main content

Disable Selection When Set Readonly for HTML Select Tag

The HTML select field is a common tool for getting user input. Its purpose is to allow the user to select an option from a list of options. The select field can be used for both single- and multiple-choice input. It is typically used when there are a limited number of options, such as in a drop-down menu.

The select field has a number of attributes that can be used to control its behavior. For example, the size attribute can be used to specify the number of options that should be displayed at once. The multiple attributes can be used to allow the user to select more than one option. The disabled attribute can be used to prevent the user from making any changes to the selected option.

Readonly attribute of the select field grey out the field but it still allows users to choose a value. Even though the field is not recognized by the form input system. This is a code snippet that can be used to disable selection for HTML select tag when the readonly attribute is set.

<form>
            <div class="form-group">
                <label>Programming Language</label>
                <select class="form-control" readonly>
                    <option value="1">Select</option>
                    <option value="2">Input</option>
                    <option value="3">Textarea</option>
                    <option value="4">Button</option>
                </select>
            </div>

            <div class="form-group">
                <input type="submit" name="submit" class="btn btn-primary" value="Save" />
            </div>
        </form>

CSS

select[readonly]
{
    pointer-events: none;
}

JavaScript

Firstly, add the disabled attribute to the select field to prevent the user from interacting with the field.

<select class="form-control" disabled="disabled">
</select>

Then remove the disabled attribute after the user submits its form.

document.querySelector("form").addEventListener("submit", function(e){
        document.getElementsByTagName("select")[0].removeAttribute("disabled");
    });

By continuing to use the site, you agree to the use of cookies.