Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A readOnly Equivalent for HTML Select Elements [duplicate]

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)

like image 697
Alan Storm Avatar asked Aug 15 '12 19:08

Alan Storm


2 Answers

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.

like image 116
Sjoerd Avatar answered Oct 19 '22 07:10

Sjoerd


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();
});
like image 3
Anonymous Avatar answered Oct 19 '22 07:10

Anonymous