Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_POST for disabled select

Tags:

html

post

php

<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

like image 682
infinityskyline Avatar asked Aug 30 '11 14:08

infinityskyline


2 Answers

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" />
like image 63
DaveRandom Avatar answered Oct 15 '22 14:10

DaveRandom


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;
        }
    }
});
like image 21
Rocket Hazmat Avatar answered Oct 15 '22 12:10

Rocket Hazmat