views:

61

answers:

3

struggling to get the value of a selected item

html-

<select name="recommendFriend" onChange="friendWall(127);return false;" id="recommendFriend">



var user = document.getElementById("recommendFriend").getAttribute("value")

im using JS on facebook

A: 

Select boxes are a bit tougher to get the value of...

 document.nameOfForm.idOfSelect.options[document.nameOfForm.idOfSelect.selectedIndex].value

should get you where you want to be.

Chris Sobolewski
A: 

<select /> tags have no value attribute. Instead, you should use the selectedIndex or the value property.

var selectElem = document.getElementById("recommendFriend");
var user = selectElem.value;

I can't remember if all modern browsers support the value property (I'm pretty certain they do), but if not, then do this:

var selectElem = document.getElementById("recommendFriend");
var selectedIndex = selectElem.selectedIndex;
var user = selectElem.options[selectedIndex].value;
Dan Herbert
i keep getting undefined for the user variable- facebook doesnt like the second solution- the selectedIndex is the probleem for some reason
chris
Some old browsers didn't support `value` on select; selectedIndex is the traditional safe way. @chris: I don't think you're picking up the right element. Check the source for other elements having the same `id="recommendFriend"` attribute (this is invalid).
bobince
(And incidentally, don't use `getAttribute` on an HTML DOM, as IE has many bugs with it. Use the direct DOM Level 1 HTML properties like `value` in this case. On form elements, the HTML `value` attribute is the initial value; the current value which you want to read may be different.)
bobince
searched the document for recommendFriend only one occurence- im using chrome and FF
chris
do `alert(selectElem.tagName)`. If it's correctly `select`, you should have no problem reading the `value` or `selectedIndex`. If it's something else, that's your problem.
bobince
A: 

i have found the problem- yet again facebook has its own ideas about JS- the solution was

var selectElem = document.getElementById("recommendFriend");
var user = selectElem.getValue()
chris