According to HTML specs, the select
tag in HTML doesn't have a readonly
attribute, only a disabled
attribute. So if you want to keep the user from changing the dropdown, you have to use disabled
.
The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
What's the best way to emulate the readonly
attribute for a select
tag, and still get the POST data?
The disabled attribute for <select> element in HTML is used to specify that the select element is disabled. A disabled drop-down list is un-clickable and unusable.
A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit.
When a textarea is disabled , it will be ignored by a parent form. However, when a textarea is readonly the contents of the textarea will still be submitted with the form even though the user cannot modify the contents.
When an item (option) is selected in DropDownList (HTML SELECT), the EnableDisableTextBox JavaScript function is executed. Inside this function, based on whether the Other option (item) is selected, the TextBox will be enabled else disabled. The HTML Markup consists of a DropDownList (HTML SELECT) and a TextBox.
You should keep the select
element disabled
but also add another hidden input
with the same name and value.
If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.
Here is a demo:
$('#mainform').submit(function() { $('#formdata_container').show(); $('#formdata').html($(this).serialize()); return false; }); $('#enableselect').click(function() { $('#mainform input[name=animal]') .attr("disabled", true); $('#animal-select') .attr('disabled', false) .attr('name', 'animal'); $('#enableselect').hide(); return false; });
#formdata_container { padding: 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <form id="mainform"> <select id="animal-select" disabled="true"> <option value="cat" selected>Cat</option> <option value="dog">Dog</option> <option value="hamster">Hamster</option> </select> <input type="hidden" name="animal" value="cat"/> <button id="enableselect">Enable</button> <select name="color"> <option value="blue" selected>Blue</option> <option value="green">Green</option> <option value="red">Red</option> </select> <input type="submit"/> </form> </div> <div id="formdata_container" style="display:none"> <div>Submitted data:</div> <div id="formdata"> </div> </div>
We could also disable all except the selected option.
This way the dropdown still works (and submits its value) but the user can not select another value.
Demo
<select> <option disabled>1</option> <option selected>2</option> <option disabled>3</option> </select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With