$_POST for disabled select

<select class="txtbx1" name="country" disabled>

<option value='FR' >FRANCE</option><option value='CH' selected>SWITZERLAND</option>
</select>

the above code is inside a form whose method is post

but echo $_POST['country'] is showing nothing.. on the other hand if I remove disabled from select $_POST['country'] is showing the correct result

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

This is how the disabled attribute works. When a form control is disabled, the value will be ignored when the form is submitted and the key will not be present in $_POST (or $_GET).

If you want the value to be present in the submitted data, but you don’t want the user to be able to change the value on the page (which I imagine is what you are trying to acheive) use readonly="readonly" instead of disabled="disabled".

EDIT

The <select> element does not have a readonly attribute. The above information still stands as it will work for <input>s and <textarea>s.

The solution to your problem here would be to disable the select and use a hidden input to send the value back to the server – e.g.

When the select is enabled:

<select class="txtbx1" name="country">
  <!-- options here -->
</select>

…and when it is disabled:

<select class="txtbx1" name="country_disabled" disabled="disabled">
  <!-- options here, with appropriate value having `selected="selected"` -->
</select>
<input type="hidden" name="country" value="value_of_field" />

Solution 2

This is the correct behavior. disabled disables the element, and does not send it’s value when a form is POSTed.

You can use JavaScript to un-disable the form before you submit it. Something like this (untested):

document.getElementById('myForm').addEventListener('submit', function() {
    for(var i = 0; i < this.children.length; i++){
        var child = this.children[i];
        if(child.disabled){
            child.disabled = false;
        }
    }
});

Solution 3

How your form tag looks like? You may have forgotten the method="post" attribute…

Solution 4

If your goal is have a "readonly select" – that is show the user what the choices are without allowing it to change and have it sent with the POST variables, you want to use "selected" on the option with the current value, and "disabled" on all the other options. This will essentially show the select with all its options but only allow the current one to be selected.

I find this more helpful than simply having a disabled select.

As others have noted, you still need to insure that the server side doesn’t accept changes to the field (as with any readonly field).

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply