Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  182] [ 6]  / answers: 1 / hits: 20357  / 12 Years ago, sat, june 23, 2012, 12:00:00

The below code doesn't it print the value.



function go(x)
{
alert(x.options.selectedIndex.value);
//location=document.menu.student.options[document.menu.student.selectedIndex].value
}


this is the html code



<select name=student onChange=go(this)>
<option selected> Student </option>
<option value=http://www.cnet.com>Attendence</option>
<option value=http://www.abc.com>Exams</option>
</select>

More From » javascript

 Answers
10

selectedIndex is a number, it doesn't have a value property.



If you have a select element which just allows single-select (as yours does), the easiest way to get its value is the select element's value property:



function go(x) {
alert(x.value);
}


Double-check that it works on the browsers you want to support, but MaryAnne (see the comments) has checked on all current major browsers and I've checked IE6, IE7, and Firefox 3.6 (e.g., older browsers), and they all work. Since it's specified in DOM2 HTML (the link above)...



But re selectedIndex, you probably meant:



function go(x) {
alert(x.options[x.selectedIndex].value);
}


I'd probably take it a bit further and be more defensive:



function go(x) {
var option = x.options[x.selectedIndex];
if (option) {
alert(option.value);
}
}


...or



function go(x) {
var option = x.options[x.selectedIndex];
var value = option && option.value;
alert(value); // Alerts undefined if nothing is selected
}


...in case there is no selected option (in which case, option will be undefined), although with your particular markup and code, I'm not aware of a user agent where the change event would be fired without there being anything selected. At least, I don't think so — I think being the reason for being defensive. :-)


[#84711] Thursday, June 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;