Matt Ratliff wrote:
Hello,
I would appreciate any assistance you have with the following
problem:
I have (as an example) an array of values as follows:
arrayvalues=new Array("0001","0003","0005") where each is the value
of an option in a select statement:
<select id="usertypes" multiple="multiple">
<option value="0033">data1</option>
<option value="0025">data2</option>
<option value="0001">data3</option>
<option value="0003">data4</option>
<option value="1234">data5</option>
<option value="0005">data6</option>
</select>
Based on my array values I would like to highlight each option whose
value cooresponds to an element of my array. I have the following
javascript code:
usertypes=document.getElementById("usertypes");
for(var j=0; j<arrayvalues.length; j++)
for(var i=0; i<usertypes.options.length; i++)
{
if(usertypes.options[i].value==arrayvalues[j])
usertypes.options[i].selected=true;
}
Problem: Script will not highlight all options associated with my
array values. However, if I add an alert statement before or after
the if statement, the script will highlight each entry as needed.
Does anyone have any ideas on why this is happening?
I used the follwing to try to repeat the problem (based on assumptions
of your code fragments):
<script>
var arrayvalues=new Array("0001","0003","0005");
function setSelects(){
usertypes=document.getElementById("usertypes");
for(var j=0; j<arrayvalues.length; j++)
for(var i=0; i<usertypes.options.length; i++)
{
if(usertypes.options[i].value==arrayvalues[j])
usertypes.options[i].selected=true;
}
}
window.onload=setSelects;
</script>
<form>
<select id="usertypes" multiple="multiple">
<option value="0033">data1</option>
<option value="0025">data2</option>
<option value="0001">data3</option>
<option value="0003">data4</option>
<option value="1234">data5</option>
<option value="0005">data6</option>
</select>
</form>
However, it appears to work as you want it to (Firefox
1.5.05/Linux/Win2k & IE6).
Maybe the problem is how you are starting the script ?
Being one of those types who prefers to avoid nested loops, let me
suggest a little change to the script:
function setSelects(){
var inverted = new Array();
for(var i=0; i<arrayvalues.length; i++){
inverted[arrayvalues[i]] = true;
}
usertypes=document.getElementById("usertypes");
for(var i=0; i<usertypes.options.length; i++)
{
var curOpt = usertypes.options[i];
curOpt.selected = inverted[curOpt.value];
}
}