简体   繁体   中英

javascript get selected text not value

Is it possible to get the selected text in the select not its value?

<select id="animals">
   <option value="mammals">Elephant</option>
   <option value="reptile">Snakes</option>
   <option value="mammals">Bear</option>
   <option value="birds">Ostrich</option>
</select>

I want to know the type of animal that is being selected.

Thank you for all your help.

function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

var text = getSelectedText('animals');

Use Document.querySelector() , Returns the first element within the document that matches the specified group of selectors.

 console.log(document.querySelector('#animals option:checked').textContent);
 <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> <select id="animals"> <option value="mammals">Elephant</option> <option value="reptile">Snakes</option> <option value="mammals">Bear</option> <option value="birds">Ostrich</option> </select>

Fiddle

jQuery:

$("#selection option:selected").text();

with pure Javascript:

this.options[this.selectedIndex].innerText

Try This

It can be done by using javascript selectedIndex and text method.

 <!DOCTYPE html> <html> <body> <p>Choose an option in the drop-down list and display that option.</p> <form> <select id="mySelect" onchange="myFunction()"> <option value="mammals">Elephant</option> <option value="reptile">Snakes</option> <option value="mammals">Bear</option> <option value="birds">Ostrich</option> </select> </form> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("mySelect"); var i = x.selectedIndex; document.getElementById("demo").innerHTML = x.options[i].text; } </script> </body> </html>

I had a similar problem whereby I wanted to output selected text (not value) into a Textarea box. I solved it this way:

     <label>Objectives :</label>
<select name="objectives" class="objectives" onchange="getObjectives(this);">
<option selected="selected">--Select Objectives--</option>
<option selected="selected">--One--</option>
<option selected="selected">--Two--</option>
</select>

<textarea rows="4" cols="30" id="objid"></textarea>

<script>
function getObjectives(sel) {
// Select option returns text instead of value of option
document.getElementById ("animals").value = sel.options[sel.selectedIndex].text;

}

   </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