af*****@gmail.com wrote:
It's been quite awhile since I've written anything in JavaScript, so
please pardon my ignorance if I'm missing the obvious. The following
code works fine in Firefox, but not in IE (unless I include an alert).
The piece of code that's giving me grief is:
function doThis() {
// alert('Activate this line makes it work');
var iSelectedValue =
document.getElementById('mySelect').options[document.getElementById('mySelect').selectedIndex].value;
Ignoring the rather horrible code, the issue appears to be related to
the select element's multiple attribute. In this case, it seems that
IE does not allocate a default selected option. doThis() is called
onclick, so when called for the very first click, the selectedIndex at
that point returns -1. There is no option with index -1 so an error
results. I suspect that the alert allows time for the click to filter
through and cause an option to be selected, hence the error doesn't
occur in that case.
There are a couple of solutions, but that depends on what you are
actually trying to do.
Incidentally, if you ctrl+click to select multiple options, you only
get the selected index of the first selected option.
I would pass 'this' from the select, so the code is more like:
function doThis(sel){
var selectedValues = [];
for (var i=0, len=sel.length; i<len; i++){
if (sel[i].selected) {
selectedValues.push(sel[i].value);
}
}
alert('You selected:\n' + selectedValues.join('\n'));
}
But you'll note that the result is still one click behind.
alert(iSelectedValue);
}
I get an "Object doesn't support this property or method" error in IE
on the first time I run the function, subsequent calls to the function
don't give me an error, but do give me screwy results.
The results are quite predictable - IE reports the previously selected
option, which indicates that onclick runs before the selectedIndex
property is changed. Doing:
<select id="mySelect" multiple="multiple" size="10"
onClick="alert(this.selectedIndex);">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Shows -1 the first time the select is clicked on.
--
Rob