[javascript] How to ensure a <select> form field is submitted when it is disabled?

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 a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.

This question is related to javascript html css forms html-select

The answer is


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


Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".

function changeSelectUserManipulation(obj, disable){
    var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
    disable = disable? !!disable : !$obj.is(':disabled');

    if(disable){
        $obj.prop('disabled', true)
            .after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
    }else{
        $obj.prop('disabled', false)
            .next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
    }
}

changeSelectUserManipulation("select_id");

I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled. This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)

Shameless plug: https://github.com/Jezternz/jq-disabled-inputs


Same solution suggested by Tres without using jQuery

<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">

   <select id="mysel" disabled="disabled">....</select>

   <input name="submit" id="submit" type="submit" value="SEND FORM">
</form>

This might help someone understand more, but obviously is less flexible than the jQuery one.


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


I use next code for disable options in selections

<select class="sel big" id="form_code" name="code" readonly="readonly">
   <option value="user_played_game" selected="true">1 Game</option>
   <option value="coins" disabled="">2 Object</option>
   <option value="event" disabled="">3 Object</option>
   <option value="level" disabled="">4 Object</option>
   <option value="game" disabled="">5 Object</option>
</select>

// Disable selection for options
$('select option:not(:selected)').each(function(){
 $(this).attr('disabled', 'disabled');
});

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.


The easiest way i found was to create a tiny javascript function tied to your form :

function enablePath() {
    document.getElementById('select_name').disabled= "";
}

and you call it in your form here :

<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">

Or you can call it in the function you use to check your form :)


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

jQuery code:

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

it dows not work with the :input selector for select fields, use this:

    jQuery(function() {

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

    });

Just add a line before submit.

$("#XYZ").removeAttr("disabled");


<select id="example">
    <option value="">please select</option>
    <option value="0" >one</option>
    <option value="1">two</option>
</select>



if (condition){
    //you can't select
    $("#example").find("option").css("display","none");
}else{
   //you can select
   $("#example").find("option").css("display","block");
}

I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well. Using jQuery:

jQuery(function($) {
    $('form').submit(function(){
        $('select option:not(:selected)', this).remove();
    });
});

I was faced with a slightly different scenario, in that I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using

$('#toSelect')find(':not(:selected)').prop('disabled',true);

I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.

// With jQuery
$('#selectbox').focus(function(e) {
    $(this).blur();
});

Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery