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:
-
-
function emulateDisabled(selectBox) {
-
for (var i=0, option; option = selectBox.options[i]; i++) {
-
if (option.disabled) {
-
option.style.color = "graytext";
-
}else{
-
option.style.color = "menutext";
-
}
-
}
-
}
-
-
function restoreEmulateDisabled(selectBox) {
-
for (var i=0, option; option = selectBox.options[i]; i++) {
-
if(option.selected && option.disabled){
-
option.selected=false;
-
}
-
}
-
}
-
-
function addEmulation(selectBox){
-
window.select_current = new Array();
-
selectBox.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
-
selectBox.onchange = function(){ restoreEmulateDisabled(this); }
-
}
-
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:
-
-
window.onload = function() {
-
if (document.getElementsByTagName) {
-
var s = document.getElementsByTagName("select");
-
if (s.length > 0) {
-
window.select_current = new Array();
-
for (var i=0, select; select = s[i]; i++) {
-
select.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
-
select.onchange = function(){ restoreEmulateDisabled(this); }
-
emulateDisabled(select);
-
}
-
}
-
}
-
}
-
A big thanks to the guy from lattimore.
cheers mate.
5 comments August 16th, 2007
