Unable to get selected value from list box in IE 8
Unable to get selected value from list box in IE 8
<select id="fileName" style="width: 100%;" size="3" name="uploadedfile">
<option i开发者_C百科d="my1Div">test1</option>
<option id="my3Div">test2</option>
<option id="my5Div">test3</option>
</select>
I am getting the value like the following
var myvalue= document.getElementById("fileName").value;
alert(myvalue);
var select = document.getElementById("fileName");
var myvalue= select.options[select.selectedIndex].value;
alert(myvalue);
select.value
appears in the DOM specification, but has never been implemented by IE. The selectedIndex
property works everywhere.
UPDATE: as anddoutoi points out in a comment to the original question, this assumes you are using a single-item select
.
var selectElement = document.getElementById("selectElementId");
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
This should be changed to:
var selectElement = document.getElementById("selectElementId");
var selectedValue = selectElement.options[selectElement.selectedIndex].text;
Changing the .value
to .text
solves the problem and is compatible with all browsers.
Your problem is with your HTML. Quoted from your comment:
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>
You have to actually specify a value for each <option>
. Try this:
<select id="fileName">
<option id="my1Div" value="test1">test1</option>
...
<option id="my5Div" value="test3">test3</option>
</select>
var listbox = document.getElementById("list");
for(var i=0; i<listbox.options.length; i++)
if(listbox.options[i].selected)
alert(listbox.options[i].value);
Something like that?
Edit: typo!
var selectElement = document.getElementById("selectElementId");
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
Code to get a vaiable columnName from the SELECT box called layerDetails.styleColumn (SELECT tag has same name and Id), that works across ALL browsers ...
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;
}
}
精彩评论