简体   繁体   English

使用 JavaScript 获取选定的选项文本

[英]Get selected option text with JavaScript

I have a dropdown list like this:我有一个这样的下拉列表:

<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>

How can I get the actual option text rather than the value using JavaScript?如何使用 JavaScript 获取实际的选项文本而不是值? I can get the value with something like:我可以通过以下方式获得价值:

<select id="box1" onChange="myNewFunction(this.selectedIndex);" >

But rather than 7122 I want cat .但不是7122我想要cat

Try options尝试选项

 function myNewFunction(sel) { alert(sel.options[sel.selectedIndex].text); }
 <select id="box1" onChange="myNewFunction(this);"> <option value="98">dog</option> <option value="7122">cat</option> <option value="142">bird</option> </select>

Plain JavaScript纯 JavaScript

var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;

jQuery: jQuery:

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

所有这些功能和随机的东西,我认为最好使用这个,并且这样做:

this.options[this.selectedIndex].text

There are two solutions, as far as I know.据我所知,有两种解决方案。

both that just need using vanilla javascript两者都只需要使用 vanilla javascript

1 selectedOptions 1 已选择选项

live demo现场演示

 const log = console.log; const areaSelect = document.querySelector(`[id="area"]`); areaSelect.addEventListener(`change`, (e) => { // log(`e.target`, e.target); const select = e.target; const value = select.value; const desc = select.selectedOptions[0].text; log(`option desc`, desc); });
 <div class="select-box clearfix"> <label for="area">Area</label> <select id="area"> <option value="101">A1</option> <option value="102">B2</option> <option value="103">C3</option> </select> </div>

2 options 2 个选项

live demo现场演示

 const log = console.log; const areaSelect = document.querySelector(`[id="area"]`); areaSelect.addEventListener(`change`, (e) => { // log(`e.target`, e.target); const select = e.target; const value = select.value; const desc = select.options[select.selectedIndex].text; log(`option desc`, desc); });
 <div class="select-box clearfix"> <label for="area">Area</label> <select id="area"> <option value="101">A1</option> <option value="102">B2</option> <option value="103">C3</option> </select> </div>


HTML: HTML:

<select id="box1" onChange="myNewFunction(this);">

JavaScript: JavaScript:

function myNewFunction(element) {
    var text = element.options[element.selectedIndex].text;
    // ...
}

DEMO: http://jsfiddle.net/6dkun/1/演示:http: //jsfiddle.net/6dkun/1/

Use -利用 -

$.trim($("select").children("option:selected").text())   //cat

Here is the fiddle - http://jsfiddle.net/eEGr3/这是小提琴 - http://jsfiddle.net/eEGr3/

To get it on React with Typescript:要使用 Typescript 在 React 上使用它:

  const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
    const {  options, selectedIndex } = event.target;
    const text = options[selectedIndex].text;
    // Do something...
  };

Using vanilla JavaScript使用原生 JavaScript

onChange = { e => e.currentTarget.options[e.selectedIndex].text }

will give you exact value if values are inside a loop.如果值在循环内,将为您提供准确的值。

Using jquery.使用 jQuery。
In your event在您的活动中

  let selText = $("#box1 option:selected").text();
  console.log(selText);

You'll need to get the innerHTML of the option, and not its value. 您需要获取选项的 innerHTML,而不是其值。

Use this.innerHTML instead of this.selectedIndex . 使用 this.innerHTML而不是 this.selectedIndex

Edit: You'll need to get the option element first and then use innerHTML. 编辑:您需要先获取选项元素,然后使用 innerHTML。

Use this.text instead of this.selectedIndex .使用this.text而不是this.selectedIndex

 <select class="cS" onChange="fSel2(this.value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select><br>

 <select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <script type="text/javascript"> "use strict";
   const s=document.querySelector(".cS");

 // options[this.selectedIndex].value
 let fSel = (sIdx) => console.log(sIdx,
     s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);

 let fSel2= (sIdx) => { // this.value
     console.log(sIdx, s.options[sIdx].text,
         s.options[sIdx].textContent, s.options[sIdx].label);
 }

 // options[this.selectedIndex].text
 // options[this.selectedIndex].textContent
 // options[this.selectedIndex].label
 // options[this.selectedIndex].innerHTML
 let fSel3= (sIdx) => {
     console.log(sIdx);
 }
 </script> // fSel

But :但 :

 <script type="text/javascript"> "use strict";
    const x=document.querySelector(".cS"),
          o=x.options, i=x.selectedIndex;
    console.log(o[i].value,
                o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
 </script> // .cS"

And also this :还有这个:

 <select id="iSel" size="3">
     <option value="one">Un</option>
     <option value="two">Deux</option>
     <option value="three">Trois</option>
 </select>


 <script type="text/javascript"> "use strict";
    const i=document.getElementById("iSel");
    for(let k=0;k<i.length;k++) {
        if(k == i.selectedIndex) console.log("Selected ".repeat(3));
        console.log(`${Object.entries(i.options)[k][1].value}`+
                    ` => ` +
                    `${Object.entries(i.options)[k][1].innerHTML}`);
        console.log(Object.values(i.options)[k].value ,
                    " => ",
                    Object.values(i.options)[k].innerHTML);
        console.log("=".repeat(25));
    }
 </script>

You can get an array-like object that contains the selected item(s) with the method getSelected() method.您可以使用getSelected()方法获取包含所选项目的类似数组的对象。 like this:像这样:

querySelector('#box1').getSelected()

so you can extract the text with the .textContent attribute.因此您可以使用.textContent属性提取文本。 like this:像这样:

querySelector('#box1').getSelected()[0].textContent 

If you have a multiple selection box you can loop through array-like object I hope it helps you😎👍如果你有一个多选框,你可以循环遍历类似数组的对象,希望对你有帮助😎👍

 function runCode() { var value = document.querySelector('#Country').value; window.alert(document.querySelector(`#Country option[value=${value}]`).innerText); }
 <select name="Country" id="Country"> <option value="IN">India</option> <option value="GBR">United Kingdom </option> <option value="USA">United States </option> <option value="URY">Uruguay </option> <option value="UZB">Uzbekistan </option> </select> <button onclick="runCode()">Run</button>

var selectionlist=document.getElementById("agents"); var selectionlist=document.getElementById("agents"); td2.innerHTML = selectionlist.children[selectionlist.selectedIndex].innerHTML; td2.innerHTML = selectionlist.children[selectionlist.selectedIndex].innerHTML;

I just copy all amazon.com "select list", you can see demo from following image.gif link.我只是复制所有 amazon.com 的“选择列表”,您可以从以下 image.gif 链接查看演示。

现在看演示

I love amazon.com "select/option" css style and javascript tricks...我喜欢 amazon.com 的“选择/选项”css 样式和 javascript 技巧......

try it now....现在就试试....

 /***javascript code***/ document.querySelector("#mySelect").addEventListener("click", () => { var x = document.querySelector("#mySelect").selectedIndex; let optionText = document.getElementsByTagName("option")[x].innerText; document.querySelector(".nav-search-label").innerText = optionText; });
 /***style.css***/ .nav-left { display: -webkit-box; display: -moz-box; display: -webkit-flex; display: -ms-flexbox; display: flex; position: static; float: none; } .nav-search-scope { display: -webkit-box; display: -moz-box; display: -webkit-flex; display: -ms-flexbox; display: flex; position: relative; float: none; top: 0; right: 0; bottom: 0; left: 0; } .nav-search-facade { position: relative; float: left; cursor: default; overflow: hidden; top: 3px; } .nav-search-label { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: #555; font-size: 12px; line-height: 33px; margin-right: 21px; margin-left: 5px; min-width: 19px; } .nav-icon { position: absolute; top: 14px; right: 8px; border-style: solid; _border-style: dashed; border-width: 4px; border-color: transparent; border-top: 4px solid #666; border-bottom-width: 0; width: 0; height: 0; font-size: 0; line-height: 0; } .nav-search-dropdown { position: absolute; display: block; top: -1px; left: 0; height: 35px; width: auto; font-family: inherit; outline: 0; margin: 0; padding: 0; cursor: pointer; opacity: 0; filter: alpha(opacity=0); visibility: visible; border: 0; line-height: 35px; }
 <!--html code--> <div class="nav-left"> <div id="nav-search-dropdown-card"> <div class="nav-search-scope nav-sprite"> <div class="nav-search-facade"> <span class="nav-search-label" style="width: auto">All</span> <i class="nav-icon"></i> </div> <select id="mySelect" class="nav-search-dropdown searchSelect" style="display: block; top: 3px" tabindex="0" title="Search in" > <option>All Departments</option> <option>Arts &amp; Crafts</option> <option>Automotive</option> <option>Baby</option> <option>Beauty &amp; Personal Care</option> <option>Books</option> <option>Computers</option> <option>Digital Music</option> <option>Electronics</option> <option>Kindle Store</option> <option>Prime Video</option> <option>Women's Fashion</option> <option>Men's Fashion</option> <option>Girls' Fashion</option> <option>Boys' Fashion</option> <option>Deals</option> <option>Health &amp; Household</option> <option>Home &amp; Kitchen</option> <option>Industrial &amp; Scientific</option> <option>Luggage</option> <option>Movies &amp; TV</option> <option>Music, CDs &amp; Vinyl</option> <option>Pet Supplies</option> <option>Software</option> <option>Sports &amp; Outdoors</option> <option>Tools &amp; Home Improvement</option> <option>Toys &amp; Games</option> <option>Video Games</option> </select> </div> </div> </div>

Try the below:试试下面的:

myNewFunction = function(id, index) {
    var selection = document.getElementById(id);
    alert(selection.options[index].innerHTML);
};

See here jsfiddle sample请参阅此处的 jsfiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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