Thursday, June 21, 2012

Using jQuery to Make a Read Only Select Field

There is no read only option for select boxes. If a select box is disabled, it does not submit values when a form is saved. This is my attempt to emulated a readonly property for a select box. I am sure there a dozens of other ways to do this, probably better than this, but this seems to work for me.

Here is an example. The first select box is set to "0". The second select box is set to "".



The select boxes both have a data attribute. It is "data-readonly" and it is set to "yes".

<select name="select01" id="select01" data-readonly="yes">
 <option value="" > -- </option>
 <option value="1" >1 - Yes </option>
 <option value="0" selected="selected">0 - No</option>
 <option value="-6" >-6 - Permanently Missing </option>
 <option value="-7" >-7 - Don't Know </option>
 <option value="-8" >-8 - Refused </option>
 <option value="-9" >-9 - Not on Form </option>
</select>

<select name="select02" id="select02" data-readonly="yes">
 <option value="" > -- </option>
 <option value="1" >1 - Yes</option>
 <option value="0"  >0 - No</option>
 <option value="-6" >-6 - Permanently Missing </option>
 <option value="-7" >-7 - Don't Know </option>
 <option value="-8" >-8 - Refused </option>
 <option value="-9" >-9 - Not on Form </option>
</select>


The script follows. It looks for all select boxes with "data-readonly='yes'" and then stores their value in another data attribute. A change function is then bound to the select that always restores the prior value on change.

<script language="JavaScript" type="text/javascript">
$(document).ready
(
 function()
 {
  var sel = $("select[data-readonly='yes']");
  
  sel.each
  (
   function()
   {
    $(this).data("prev",$(this).val());
    
    $(this).change
    (
     function(data)
     {
      var obj = $(this);
      
      obj.val(obj.data("prev"));
      obj.data("prev",obj.val());
     }
    );
   }
  )
 }
);
</script>

No comments:

Post a Comment