[zz]Disable options in a multiple select – Javascript for IE

http://www.danieltome.com/blog/2007/08/16/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.  
posted @ 2010-07-06 21:27  bettermanlu  阅读(386)  评论(0编辑  收藏  举报