无法从IE 8中的列表框中获取选定的值

时间:2009-11-12 11:45:55

标签: javascript html dom

无法从IE 8中的列表框中获取选定的值

<select id="fileName" style="width: 100%;" size="3" name="uploadedfile">
<option id="my1Div">test1</option>
<option id="my3Div">test2</option>
<option id="my5Div">test3</option>
</select>

我得到的值如下

var myvalue= document.getElementById("fileName").value;
alert(myvalue);

6 个答案:

答案 0 :(得分:7)

var select = document.getElementById("fileName");
var myvalue= select.options[select.selectedIndex].value;
alert(myvalue);

select.value出现在the DOM specification中,但IE从未实现过。 selectedIndex属性无处不在。

更新:正如anddoutoi在对原始问题的评论中指出的,这假设您使用的是单项select

答案 1 :(得分:6)

var selectElement = document.getElementById("selectElementId");
var selectedValue = selectElement.options[selectElement.selectedIndex].value;

这应该改为:

var selectElement = document.getElementById("selectElementId");
var selectedValue = selectElement.options[selectElement.selectedIndex].text;

.value更改为.text可解决问题,并与所有浏览器兼容。

答案 2 :(得分:4)

您的问题与您的HTML有关。引自您的评论:

No simple Option box <select id="fileName" style="width: 100%;" size="3" name="uploadedfile"> <option id="my1Div">test1</option> <option id="my3Div">test2</option> <option id="my5Div">test3</option> </select>

您必须为每个<option>实际指定一个值。试试这个:

<select id="fileName">
    <option id="my1Div" value="test1">test1</option>
    ...
    <option id="my5Div" value="test3">test3</option>
</select>

答案 3 :(得分:1)

var listbox = document.getElementById("list");
for(var i=0; i<listbox.options.length; i++)
    if(listbox.options[i].selected)
        alert(listbox.options[i].value);

那样的东西?

编辑:错字!

答案 4 :(得分:1)

var selectElement = document.getElementById("selectElementId");
var selectedValue = selectElement.options[selectElement.selectedIndex].value;

答案 5 :(得分:0)

从名为 layerDetails.styleColumn 的SELECT框中获取可变 columnName 的代码(SELECT标记具有相同的名称和ID),适用于所有浏览器... < / p>

var columnName = document.getElementsByName('layerDetails.styleColumn')[0].value;
if ( columnName == null || columnName == '' )
  {
  columnName = document.getElementById('layerDetails.styleColumn').value;
  }

if ( columnName == null || columnName == '' )
  {
  var select = document.getElementById('layerDetails.styleColumn');
  columnName= select.options[select.selectedIndex].value;
  if ( columnName == null || columnName == '' )
    {
    columnName= select.options[select.selectedIndex].text;
    }
  }