开发者

read selected value from select tag of HTML using javascript code

开发者 https://www.devze.com 2023-03-19 17:16 出处:网络
My HTML code is as: <div id=\"detail\"> <div class=\"d_left\"> Page <strong>1</strong> of 107

My HTML code is as:

 <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 selected value from <select name="featured" size="1" id="item1">. How can I do this using JavaScript?


document.getElementById("item1").value;


More Elegant variant of sushil bharwani solution

function $(id){return document.getElementById(id);}

var select = $("item1");
select.onchange = function() {
    var selIndex = select.selectedIndex;
    var selValue = select.options(selIndex).innerHTML;
}

As Shadow Wizard do not like this solution I hope he will like that:

var select = document.getElementById("item1");
select.onchange = function() {
    var selIndex = select.selectedIndex;
    var selValue = select.options(selIndex).innerHTML;
}

The main idea in these two example is to reduce the usage of getElementById. No point to execute it more than once - thus minimizing the 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");



document.getElementById("item1").onchange = function(){
var selIndex = document.getElementById("item1").selectedIndex;
var selValue = document.getElementById("item1").options[selIndex].innerHTML;
}


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>

Here is how i solved my problem for selecting eu countries (i have removed most of them to make my codes shorter).. as im new to javascript.. i still need to learn javascript libraries.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号