tags:

views:

81

answers:

4

Hi,

I would like to know if there is anything wrong with the below statement.

document.getElementById(monthId).options[document.getElementById(monthId).selectedIndex].value

Am asking this because, sometimes it seems to work fine and the rest of the time, it throws up an error - Object doesn't support this property or method.

BTW, monthId is the clientID of the dropdown present in a gridview in an asp.net page.

Thanks!

A: 

It's hard to evaluate without some more code as context. But without sanity checks around this line of code I would expect it to fail with an index out of bounds type exception when there is no selected index.

Matthew Vines
Guys, Am not sure if there are any issues with that sentence, but changing my logic a bit (for avoiding the use of the problematic statement) made things to work. Am selecting this as my answer as the problem could have been somewhere else eventhough the error was being thrown for that line.
+2  A: 

If no value is selected in the dropdown list, selectedIndex would be -1.

jdv
A: 

I tend to error check when using getElementById. I would expect that that is where your problem is.

Try this, and then test it in a debugger, but I will put an alert in.

var elem = document.getElementById(monthId);
if (elem.options) {
  options[document.getElementById(monthId).selectedIndex].value
} else {
  alert("elem doesn't have an options property");
}

You may want to not assume that the value property exists either, and do the same basic thing as I did here.

Once you get it working smoothly, where you know what is going to happen, you can start to remove the unneeded variables and go back to your original line, but for debugging, it is simpler to have one operation on each line and use separate variables, so that the debugger can show you what is happening.

You may want to understand the difference between undefined and null, and there are various pages on this topic but this one isn't too bad.

http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-2F00-EcmaScript.aspx

James Black
A: 

You can debug your problem by adding a breakpoint to your code in IE development tools, Firebug, Opera dragonfly or Chrome development tools and check your values.

Or you could add alert statements to check your values. Personally i think the code goes awry when selectedIndex is -1 (selectedIndex = -1 would occur when nothing is selected). Check for yourself:

alert(document.getElementById(monthId)); // Returns null if nothing is found
alert(document.getElementById(monthId).selectedIndex); // If the selectedIndex is below 0 it could cause your error

document.getElementById(monthId).options[document.getElementById(monthId).selectedIndex].value
Codemonkey