Search code examples
javascripthtmldomprototypejs

A readOnly Equivalent for HTML Select Elements


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)


Solution

  • 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.