Lock HTML select element, allow value to be sent on submit

19,070

Solution 1

This works:

$('.abc :not(:selected)').attr('disabled','disabled');

jQuery will still be looping through the elements behind the scenes, but I seriously doubt you will have performance issues unless your select has thousands of elements (in which case your usability issues will far out weigh the performance issues). The original code must have been doing something wrong.

Solution 2

This works fine

<select disabled="true">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">thre</option>
</select>

Solution 3

Add a hidden field to your form and onsubmit take the value from the select and place it in the hidden field's value

As per the HTML spec, readonly is not supported by the select tag

Solution 4

The element does not accept readonly attribute. Readonly is a wrapper that fix this.
Try this:
https://github.com/haggen/readonly

Solution 5

"select" does not have a readonly attribute. It has only disabled attribute.

http://www.w3schools.com/TAGS/att_select_disabled.asp

So your best best is:

$('.abc').each(function(element) {
    $(this).attr('disabled','disabled');
});

HTH

Share:
19,070
Ben Everard
Author by

Ben Everard

I'm Ben, co-founder and developer at The Idea Bureau.

Updated on June 05, 2022

Comments

  • Ben Everard
    Ben Everard almost 2 years

    I have a select box (for a customer field) on a complex order form, when the user starts to add lines to the order they should not be allowed to change the customer select box (unless all lines are deleted).

    My immediate thought was that I could use the disabled attribute, but when the box is disabled the selected value is no longer passed to the target.

    When the problem arose a while ago one of the other developers worked around this by looping through all the options and disabling all but the selected option, and sure enough the value was passed to the target and we've been using since. But now I'm looking for a proper solution, I don't want to loop through all the options because are data is expanding and it's starting to introduce performance issues.

    I'd prefer not to enable this / all the elements when the submit button is hit.

    How can I lock the input, whilst maintaining the selected option and passing that value to the target script? I would prefer a non-JavaScript solution if possible, but if needed we are running jQuery 1.4.2 so that could be used.

    Edit

    I've tried to use the readonly attribute with little success, here's the jQuery code I'm using:

    $('.abc').each(function(element) {
        $(this).attr('readonly','readonly');
    });
    

    When inspecting the element with Firebug the readonly attribute had been set, but I can still change the value in the select box?!