I have a question about the use of the indexOf(). 😮
I have created the script below to demonstrate the problem that I have encountered.
I have in the script, two version of a function to populate a dynamic array that is used to create a drop down box of choices.
In the IE_version, I use the indexOf() function to check for duplicated last names in an array.
In the FF_version, I create a string of the last names and use the indexOf() function to do a similar duplicated last name check.
Both versions work well in FF.
In the IE_version, running MSIE, I get an error that the method cannot be used this way.
Is this a known error OR an error on my part because I’m using the indexOf() function incorrectly?
Here’s the script. Is there an explanation of why the IE_version fails when running MSIE browser? ?
[code]
<html>
<head>
<title>Error in MSIE</title>
<script type=”text/javascript”>
var Candidates = [‘Mouse, Mickey’,’Duck, Donald’,
‘Fudd, Elmer’,’Flintstone, Fred’,’Oop, Ally’, // original names
‘Mouse, Minnie’,’Fudd, Elmer’,’Duck, Donald’,
‘Mouse, Mickey’,’Duck, Daffy’, // some last name duplicates
‘Boop, Betty’];
var Items = [];
// Following works in FF version only, NOT MSIE — why ???
function IE_version(IDS) {
for (i=0; i<Candidates.length; i++) {
tmp = Candidates[i].split(‘, ‘);
if (Items.indexOf(tmp[0]) == -1) { Items.push(tmp[0]); }
// both above and below should work, but do not in MSIE ???
// is indexOf() not a valid function to search an array? appears to work on strings only?
// if (Items.indexOf(tmp[0]) == -1) { Items[Items.length] = tmp[0]; } // same as a ‘push’
}
CreateSelect(IDS);
}
// Following works in both MSIE and FF browsers
function FF_version(IDS) {
str = ”;
for (i=0; i<Candidates.length; i++) {
tmp = Candidates[i].split(‘, ‘);
str = Items.join(‘|’);
if (str.indexOf(tmp[0]) == -1) { Items.push(tmp[0]); }
}
CreateSelect(IDS);
}
function CreateSelect(IDS) {
var sel = document.getElementById(IDS);
sel.options.length=0;
sel.options[0]=new Option(‘[SELECT]’,”,true,true);
for (var z=0;z<Items.length;z++){
sel.options[sel.options.length]=new Option(Items[z],Items[z],true,true);
}
sel.options[0].selected = true;
}
</script>
</head>
<body>
<select id=”Pick1″></select>
<button onClick=”IE_version(‘Pick1’);return false”>IE-error | FF-ok</button>
<button onClick=”FF_version(‘Pick2’);return false”>IE-ok | FF-ok</button>
<select id=”Pick2″></select>
</body>
</html>