16

I want a read-only "select" element to be not selectable, the same behavior as the readonly input box.

In the code below, you cannot change the value for the input box with the value "abc". However, you can still change the selection in the drop. I can't use "disabled" attribute because I still need to send these values to the server.

<input type="text" readonly="readonly" value="abc">

</input>

<select readonly="readonly">
  <option>Item ABC</option>
  <option>Item XYZ</option>
</select>

https://jsfiddle.net/6Lu1jpLx/

Syakur Rahman
  • 2,056
  • 32
  • 40
user1187968
  • 7,154
  • 16
  • 81
  • 152
  • Possible duplicate of [Disable select form field but still send the value](http://stackoverflow.com/questions/1191113/disable-select-form-field-but-still-send-the-value) – tcooc Sep 15 '16 at 18:15

3 Answers3

15

Simplist way to resolve this would be to use the below line:

$("#MySelect").css("pointer-events","none");

However, the following worked for me where in my case I wanted my Select to still have the disabled cursor - setting 'pointer-events' to 'none' will no longer show cursor as 'not-allowed'.

JQUERY

var isReadOnly = $("#MyCheckbox").prop("checked"); 
var domElements = $("#MyInput, #MySelect");

$(domElements).prop("readonly", isReadOnly);
$(domElements).toggleClass("my-read-only-class", isReadOnly);
$(domElements).find("option").prop("hidden", isReadOnly);

CSS

.my-read-only-class 
{   
   cursor: not-allowed;
}

JSFiddle https://jsfiddle.net/xdddzupm/

Claire
  • 414
  • 1
  • 5
  • 17
  • Thank you so much for this solution. I wish this solution was proliferated further on the internet. – Peter Klipfel Feb 14 '18 at 22:53
  • This almost works, but by using `pointer-events: none`, the select element can no longer receive focus by clicking on it. This is important for a accessibility reason. (We should not assume everyone can use both mouse and keyboard) – CookieEater Aug 09 '20 at 10:49
9

style="pointer-events: none;"

Is worked for me

<select style="pointer-events: none;">
  <option>Item ABC</option>
  <option>Item XYZ</option>
</select>
HSP
  • 345
  • 4
  • 4
3

$("select :selected").each(function(){
    $(this).parent().data("default", this);
});

$("select").change(function(e) {
    $($(this).data("default")).prop("selected", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select disabled>
    <option value="foo1">foo1</option>
    <option value="bar1" selected="selected">bar1</option>
    <option value="test1">test1</option>
</select>
Try below code

<select>
    <option value="foo1">foo1</option>
    <option value="bar1" selected="selected">bar1</option>
    <option value="test1">test1</option>
</select>
Dhaarani
  • 1,350
  • 1
  • 13
  • 23