开发者

$_POST for disabled select

开发者 https://www.devze.com 2023-04-01 19:09 出处:网络
<select class=\"txtbx1\" name=\"country\" disabled> <option value=\'FR\' >FRANCE<开发者_JS百科/option><option value=\'CH\' selected>SWITZERLAND</option>
<select class="txtbx1" name="country" disabled>

<option value='FR' >FRANCE<开发者_JS百科/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


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" />


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;
        }
    }
});


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消