Disable selection when set html select tag as readonly

HTML select field is a common way to get user input. However, when you need the field to be read-only, it can become difficult because users can still change the value of a selection using the select field’s arrow despite the value is not change. This blog post will show you how to stop this from happening without having any negative consequences on your user experience.

Select fields in HTML are typically used for a user to pick one or more options. These can be inputted via the keyboard, mouse, or touchscreen. But what if you want to prevent the option from being changed? There are many ways to block people from changing things in your HTML select field. You can use JavaScript, jQuery, or CSS.

Let’s using different approach to handle the HTML form below:

<form>
        	<div class="form-group">
        		<label>Programming Language</label>
        		<select class="form-control" readonly>
        			<option value="kotlin">Kotlin</option>
        			<option value="java">Java</option>
        			<option value="flutter">Flutter</option>
        			<option value="reactnative">React Native</option>
        		</select>
        	</div>

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

Using CSS

User can still select a read-only select because of the arrow on the right side of the field. We can just use CSS to disable click events of the arrow.

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

When user presses Tab to switch field in a form, they can still trigger the drop down event. That’s why in the HTML code of the select field, we need to set its tabindex to -1.

<select class="form-control" readonly tabindex="-1">
...

Using JavaScript

This approach sets select field’s state in 2 steps.

  • When the field is first loaded, set its state to disabled to prevent user’s interaction.
  • When the form is submitted, remove the disabled state to allow its value to be passed.
<select class="form-control" disabled="disabled">
...
document.querySelector("form").addEventListener("submit", function(e){
		document.getElementsByTagName("select")[0].removeAttribute("disabled");
	});

Using jQuery

It is the same as JavaScript method but switch the language to jQuery for those who love to use this framework.

$(function(){
		$('form').on('submit', function(){
			$('select').removeAttr('disabled');
		});
	});

Leave a Comment

Your email address will not be published. Required fields are marked *

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

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close