9

Is there an attribute or technique for HTML select fields that's equivalent to readOnly="true" for HTML inputs?

I have an form select field I'd like to disable, but still pass on when the form is posted. If this were an HTML input, I'd do something like this

$('select_id').setAttribute('readOnly', 'true');

and the browser would render the field as un-editable, but it's value would still be passed to the backend. I'd like something similar for an HTML select, but doing the following

$('#select_id').setAttribute('readOnly', 'true');

doesn't work. The attribute is successfully added to the DOM, but the browser still renders it as selectable.

I realize I could do the following

$('#input_id').disabled();

but when a field is disabled its value isn't passed through to the backend.

I'd like a way to disable this select field but still pass in on to the backend.

(examples use Prototype JS, but I'm interested in any general solution)

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
Alana Storm
  • 164,128
  • 91
  • 395
  • 599

2 Answers2

22

Disable all but the selected option:

<select>
<option disabled="disabled">1</option>
<option selected="selected">2</option>
<option disabled="disabled">3</option>
</select>

This way the dropdown still works (and submits its value) but the user can not select another value.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
3

add disabled class:

.disabled{
   color: grey;
}

if class present use prevent default on focus and on click, and dbl click:

$('#el').bind('click dblclick focus').function(event){
   if ($(this).hasClass('disabled')) event.preventDefault();
});
Anonymous
  • 4,692
  • 8
  • 61
  • 91