views:

1078

answers:

4

I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.

The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?

Two possibilities I'm considering include:

  • Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
  • Add an onclick event to the submit button so that it enables all of the disabled dropdown menus before submitting the form.
+3  A: 
<select disabled="disabled">
    ....
</select>
<input type="hidden" name="select_name" value="selected value" />

Where select_name is the name that you would normally give the <select>.

Another option.

<select name="myselect" disabled="disabled">
    <option value="myselectedvalue" selected="selected">My Value</option>
    ....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />

Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.

If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.

Jordan S. Jones
this sounds like the only viable option. If you use jQuery or javascript you can try to add the value when submitting in a submit handler.
Phillip Whelan
+1  A: 

Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.

Byron Whitlock
A: 

Disable the fields and then enable them before the form is submitted:

jQuery code:

jQuery(function($) {

    $('form').bind('submit', function() {
        $(this).find(':input').removeAttr('disabled');
    });

});
Tres
A: 

Another option is to use the readonly attribute.

<select readonly="readonly">
    ....
</select>

With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.

Edit:

Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:

  • Read-only elements receive focus but cannot be modified by the user.
  • Read-only elements are included in tabbing navigation.
  • Read-only elements may be successful.

When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls

Phillip Whelan
False. http://www.w3.org/TR/html401/interact/forms.html#adef-readonly
Carlos Rendon
Why is what I said false?
Phillip Whelan
The control is NOT grayed out and the user CAN edit it.You failed to read the whole section and I quote:"The following elements support the readonly attribute: INPUT and TEXTAREA."
Carlos Rendon