PDA

View Full Version : derr!! How do you find the selectedIndex of a MULTIPLE select box?


BrightNail
03-18-2003, 10:09 PM
hey all,
I was trying to use my "normal" method to find the selected element in a select box and apply it to a MULTIPLE select box, but I always get a 'undefined' value...is it different accessing this sort of element?

document.formname.elementname.options[document.formname.elementname.selectedIndex].value

but this doesn't seem to work on a Multiple select..what gives?

any help appreciated..

BrightNail

beetle
03-18-2003, 10:17 PM
Are you wanting all the indexes? Or just the first?

selectedIndex on a MULTIPLE should return the first selected index. Otherwise, you'd have to iterate over the options and check the selected property for each.

cheesebagpipe
03-18-2003, 10:23 PM
Think this works...

function getOpts(oSelect) {
var opt, i = 0, selVals = new Array();
while (opt = oSelect[i++]) if (opt.selected) selVals[selVals.length] = opt.value;
return selVals;
}

From same form:
var selected_values = getOpts(myselect)

From anywhere:
var selected_values = getOpts(document.myform.myselect)

Returns: array with selected values

BrightNail
03-18-2003, 10:45 PM
good questions..

all I need to know is if AT LEAST one has been selected hightlighted??......in other words, if ONE has been selected or MANY I want the form to submit, otherwise throw an alert..

brightnail

beetle
03-18-2003, 11:03 PM
You can use cheesebagpipe's function, and check the length of the returned array. If it's 0, none were selected and you can throw an error.

if ( selected_values.length == 0 )
// error
else
// one or more selected