Using the HTTPRequest Object. I have a list and when an item (<option>) element in the list is clicked I want to do something. But I want to know what item in the list was clicked, i.e. the exact text in the <option> tag. How can I do that? I gave an example html document, and the javascript code i'm using. Any help would be great, thanks function listChange( evt ) { evt = (evt) ? evt : ((window.event) ? window.event : null); //check for an event if (evt) //there was a change in the list (another item was clicked) { var select = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); if ( select && select.options.length > 1 ) //list has more than one option in it { //select.value gives me an index for the array holding the list's <option> //elements. How can I directly access that index value in select.options, and get //the text inside the option element? //select.options[ select.value ] seems to return the object i'm after, I think? But //still don't know how to get at its text inside. } } } Code (markup): an example of an html document <form> <select size ="10" id="list" onchange="listChange(event)"> <option value"">Some random option</option> </select> </form> Code (markup):
<script> function listChange() { var x=document.getElementById("list").options[document.getElementById("list").selectedIndex].value; alert(x); } </script> </head> <body> <form> <select size ="10" id="list" onchange="listChange()"> <option >Some random option </option> </select> </form> check out this code, the mistake with your code .. i dont know .. i just went through your objective and thought this will help you out, the mistake what i can see is <option value="">Some random option </option> here value="" is the culprit ... document.getElementById("xyz").options[1].value will first look for the value attribute in the option tag and if it not there it will give back the text inside it .. if the attribute value="" is there then obviously it will return "" i.e blank as the value
I'm sorry but it seems like that your solution will not work in IE, though it does a nice job in FireFox. I believe the IE will not look for the text when there's no value attribute. Here's my suggestion: function listChange() { var x=document.getElementById("list").options[document.getElementById("list").selectedIndex]; var selectedText = x.firstChild.nodeValue; alert(selectedText); } I have tested it in FF 2.0+, IE 7.0 , Opera 9.0 and Safari 3.0, all of them works fine. Regards,