Read selected value from select HTML tag using javascript code
My HTML code looks like this:
<div id="detail"> <div class="d_left"> Page <strong>1</strong> of 107 </div> <div class="d_center"> <table> <tr> <td><a href="#">Previous</a> | <a href="#">Next</a> <img src="/webProject/store/images/arrow.png" align="absmiddle" alt=""> </td></tr></table> </div> <div class="d_right"> Sort by: <select name="featured" size="1" id="item1"> <option>Featured Items1</option> <option>Featured Items2</option> <option>Featured Items3</option> <option>Featured Items4</option> </select> </div> </div> Now I want to read the selected value from <select name="featured" size="1" id="item1"> . How to do it using JavaScript?
Read more Elegant solution sushil bharwani
function $(id){return document.getElementById(id);} var select = $("item1"); select.onchange = function() { var selIndex = select.selectedIndex; var selValue = select.options(selIndex).innerHTML; } How the Shadow Wizard does not like this solution. Hope he likes it:
var select = document.getElementById("item1"); select.onchange = function() { var selIndex = select.selectedIndex; var selValue = select.options(selIndex).innerHTML; } The main idea in these two examples is to reduce the use of getElementById. It makes no sense to execute it more than once - this way minimizes access to the DOM .
For those who feel brave enough :) there is this new thing querySelector() mdn , msdn IE dev center , msdn , w3 spec :
var select = document.querySelector("#item1"); function delivery(x){ var country = x.value; document.getElementById('lala').innerHTML = country; } <div id="lala"></div> <form action="" method="post"> <select name="country" id="country" onChange="delivery(this)"> <option value='lala'>Select Country</option> <option value='United_Kingdom'>United Kingdom</option> <option value='Russia'>Russia</option> <option value='Ukraine'>Ukraine</option> <option value='France'>France</option> <option value='Spain'>Spain</option> <option value='Sweden'>Sweden</option> </select> </form> This is how I solved my problem for choosing EU countries (I deleted most of them to make my codes shorter) .. how are they new to javascript .. I still need to study javascript libraries.