CSS HTML

How to apply readonly in a select input

January 18, 2022

How to apply readonly in a select input

In this article we will learn how to apply readonly in a select, that is, make it impossible to have its options selected.

How to apply readonly in a select cover

What’s up programmer, ok? Let’s learn something new!

The readonly attribute doesn’t work in select by itself, we need to make a few more tweaks so that the behavior is what we want

So let’s build an example HTML structure:

<form>
 <select>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
 </select>
</form>

This is the return in the browser:

Okay, now the input is enabled, let’s make the necessary changes to make it readonly:

<select tabindex="-1" aria-disabled="true">

Firstly in HTML, let’s add tabindex=”-1″, not allowing users to access the field via tab key

Then aria-disable=”true”, a way of informing that this field is disabled for screen readers, thinking about accessibility

Now in CSS:

select {
 background: #EEE; 
 pointer-events: none;
 touch-action: none;
}

Here we include a gray background, to give the appearance of a readonly field, just as a visual effect

Then we remove the click and touch effects (mobile), with pointer-events: none and touch-action: none

Ready, our select readonly is ready, see how it turned out:

Remembering that there must be more ways to apply readonly in a select, but this one is very simple and effective

And mainly without fix-its, using only native resources of HTML and CSS languages

Conclusion

In this article we learned how to leave a select as a readonly input

It was necessary to change the HTML a little for accessibility reasons and also for the possibility of accessing it with the tab

Want to leran more HTML? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x