Friday, April 22, 2011

Once and for All How to Make a Dropdown Read Only and Still Get the Value From it

If you are a web programmer one of the most annoying things you have probably run across is the inability to make a dropdown (HTML Select tag) box read only. And another thing you don't like is reading some long post that really doesn't help you solve the issue you are trying to solve. So without taking anymore of your time, here is the code.
<head>
<script type="text/javascript">

           function DisableField(fld){
                    var origfld = document.getElementById(fld);
                    var hidfld = document.createElement("input");
                    hidfld.setAttribute("type", "hidden");
                    hidfld.setAttribute("name", origfld.name);
                    hidfld.setAttribute("id", origfld.id);
                    hidfld.setAttribute("value", origfld.value);
                    origfld.id = fld + '_disabled';
                    origfld.name = fld + '_disabled';
                    origfld.disabled = true;
                    document.getElementById("PageForm").appendChild(hidfld);
           }
</script>
</head>
<form id="PageForm">


<select name="Shop" id="Shop" >
        <option >Select Shop</option>

        <option >Shop1</option>
</select>


<!-- This has to go below the select field -->
<script type="text/javascript">DisableField('Shop');</script>

</form>

So what it does in short is you send it a field name and it renames the field and then creates a hidden field with the name and ID of the original field. So what you get is a disabled dropdown and a hidden field that contains the original value.