Posts filed under 'Javascript'

Disable options in a multiple select – Javascript for IE

Yeah, you might be amazed if you thought that just setting the option to disabled would work, even in IE7.
But it looks like it only works on proper browsers.

I searched the net everywhere to see how other people were doing it and I found this method (from: www.lattimore.id.au) to be the best one for my needs. I made some updates to it: I was using a multiple select list and also because I was creating the select box from an AJAX response. So here’s the code:

  1.  
  2. function emulateDisabled(selectBox) {
  3.  for (var i=0, option; option = selectBox.options[i]; i++) {
  4.         if (option.disabled) {
  5.                 option.style.color = "graytext";
  6.         }else{
  7.                 option.style.color = "menutext";
  8.         }
  9.  }
  10. }
  11.  
  12. function restoreEmulateDisabled(selectBox) {
  13.  for (var i=0, option; option = selectBox.options[i]; i++) {
  14.         if(option.selected && option.disabled){
  15.                 option.selected=false;
  16.         }
  17.  }
  18. }
  19.  
  20. function addEmulation(selectBox){
  21.  window.select_current = new Array();
  22.  selectBox.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
  23.  selectBox.onchange = function(){ restoreEmulateDisabled(this); }
  24. }
  25.  

If you are generating your select element with AJAX, just call emulateDisabled(your_select_box);
on the onComplete function.
If you would like to have all your select elements to have this functionality then add this onload function:

  1.  
  2. window.onload = function() {
  3.  if (document.getElementsByTagName) {
  4.         var s = document.getElementsByTagName("select");
  5.         if (s.length > 0) {
  6.                 window.select_current = new Array();
  7.                 for (var i=0, select; select = s[i]; i++) {
  8.                         select.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
  9.                         select.onchange = function(){ restoreEmulateDisabled(this); }
  10.                         emulateDisabled(select);
  11.                 }
  12.         }
  13.  }
  14. }
  15.  

A big thanks to the guy from lattimore.
cheers mate.

10 comments August 16th, 2007


Calendar

July 2010
M T W T F S S
« May    
 1234
567891011
12131415161718
19202122232425
262728293031  

Posts by Month

Posts by Category