简体   繁体   中英

How to get the value of an option in javascript parsing

Good day am having an HTML code in which i intend to get the innerText of a selected option

<div class="bag-option">
<div class="bag-option-label">colour:</div>
<div class="bag-option-control">
    <select name='select-colour-0' id='select-colour-0' onchange="onColourSelected(this, '0', '1', 'style-img-thb-', '_WLG.jpg', '_WXL.jpg', '_SKC.jpg');displayUpdateMsg();return false;">
        <option value="0" selected>orchid pink</option>
    </select>
</div>

You can get using:

document.getElementById("select-colour-0").getElementsByTagName("option")[document.getElementById("select-colour-0").selectedIndex].innerHTML

What exactly the code does is:

  1. Select the <select> tag.
  2. Get find all the <option> tags.
  3. Get the selectedIndex of the <select> .
  4. Get the particular <option> tag with the selectedIndex .
  5. Get the innerHTML of the <option> which is always a text.

A working demo of the code is below...

Snippet

 <select name='select-colour-0' id='select-colour-0' onchange="onColourSelected(this, '0', '1', 'style-img-thb-', '_WLG.jpg', '_WXL.jpg', '_SKC.jpg');displayUpdateMsg();return false;"> <option value="0" selected>orchid pink</option> </select> <script> alert(document.getElementById("select-colour-0").getElementsByTagName("option")[document.getElementById("select-colour-0").selectedIndex].innerHTML); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM