Russell Campbell wrote:
Posting again, since my first attempt never appeared:
In the onClick method of a listbox, I am attempting to retrieve the
selectedIndex property. The listbox is set up to allow multiple selections.
Unfortunately, the property returns -1. Clicking again returns the proper
result. Yet when I do the same thing on the same listbox after changing it
to allow only one entry to be selected, it always returns the proper result
on the first click. This is a pain. Is there any way to get the proper
value during the onClick when the listbox is set to allow multiple entries?
Thanks,
Russell Campbell
<form name="myForm">
<select multiple onchange="alert(getSelectedIndexes(this));">
<option value="1">1</option>
<option value="1">1</option>
<option value="1">1</option>
<option value="1">1</option>
<option value="1">1</option>
<option value="1">1</option>
</select>
</form>
<script type="text/javascript">
function getSelectedIndexes(selObj) {
if (selObj.type == 'select-one') {
return new Array(selObj.selectedIndex);
} else {
var indexes = new Array();
for (var i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
indexes.push(i);
}
}
return indexes;
}
}
</script>
The function returns an array. Using alert() calls .toString() on the returned
on the array, which returns [theArray].join(","), that's why you get a
comma-delimited list in the alert().
To use the returned array to do something useful, you'd have to iterate through
it.
The other alternative is to have the function return an associative array:
function getSelectedIndexes(selObj) {
var indexes = new Object();
if (selObj.type == 'select-one') {
indexes['idx' + selObj.selectedIndex] = true;
return indexes;
} else {
for (var i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
indexes['idx' + i] = true;
}
}
return indexes;
}
}
Now you could test for a particular item being selected directly:
onchange="if (getSelectedIndexes(this)['idx4']) { alert('4th index is
selected');"
--
| Grant Wagner <gw*****@agricoreunited.com>
* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html
* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp
* Netscape 6/7 DOM Reference available at:
*
http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 6/7 and Mozilla
*
http://www.mozilla.org/docs/web-deve...upgrade_2.html