【问题标题】:Get selected option text with JavaScript使用 JavaScript 获取选定的选项文本
【发布时间】:2013-02-05 06:08:52
【问题描述】:

我有一个这样的下拉列表:

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

如何使用 JavaScript 获取实际的选项文本而不是值?我可以通过以下方式获得价值:

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

但我想要cat而不是7122

【问题讨论】:

标签: javascript html dom drop-down-menu


【解决方案1】:

尝试选项

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>

【讨论】:

  • 尝试使用正则表达式时的第一条规则——继续搜索堆栈溢出,直到你看到不需要正则表达式的解决方案——干杯:)
  • onchange 不用大写 c 写起来更干净
  • multiple HTML 选择标签场景在哪里?
  • 我想说今天的首选方式是使用selectedOptions。这也解决了@Nitrodist 的问题。
【解决方案2】:

纯 JavaScript

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

jQuery:

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

【讨论】:

  • @mplungjan 为什么不在这里评论一下,jQuery 使用.textContent.innerText 进行.text() 方法操作?它不符合标准,完全错误,因为它不使用.text。反对票在哪里?
  • @mplungjan 不是innerHTMLinnerText 更差。
  • 我看到了选项:{ get: function( elem ) { var val = elem.attributes.value;返回 !val || val.specified ? elem.value : elem.text;} 在 1.9
【解决方案3】:

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

this.options[this.selectedIndex].text

【讨论】:

    【解决方案4】:

    据我所知,有两种解决方案。

    这两者都只需要使用香草 javascript

    1 个选定选项

    现场演示

    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 个选项

    现场演示

    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>

    【讨论】:

      【解决方案5】:

      HTML:

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

      JavaScript:

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

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

      【讨论】:

      • this comment 自从你修复了你的代码后,我删除了我们的对话
      【解决方案6】:

      使用-

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

      这是小提琴 - http://jsfiddle.net/eEGr3/

      【讨论】:

      • 问题在哪里提到了 jQuery?
      【解决方案7】:

      React / 最新的 JavaScript

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

      如果值在循环内,将为您提供准确的值。

      【讨论】:

      • 你是说Java还是JavaScript?
      【解决方案8】:

      您需要获取选项的 innerHTML,而不是其值。

      使用this.innerHTML 代替this.selectedIndex

      编辑:您需要先获取 option 元素,然后再使用 innerHTML。

      使用this.text 而不是this.selectedIndex

      【讨论】:

      • 这是错误的。它将抓住&lt;select&gt; 元素的innerHTML
      【解决方案9】:
       <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
      

      但是:

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

      还有这个:

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

      【讨论】:

        【解决方案10】:

        要在 React 上使用 Typescript:

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

        【讨论】:

          【解决方案11】:

          使用 jquery。
          在您的活动中

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

          【讨论】:

            【解决方案12】:

            我只是复制所有 amazon.com 的“选择列表”,你可以从下面的 image.gif 链接看到演示。

            我喜欢 amazon.com 的“选择/选项”css 样式和 javascript 技巧...

            现在试试....

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

            【讨论】:

              【解决方案13】:

              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>

              【讨论】:

              • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
              【解决方案14】:

              试试下面的:

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

              参见here jsfiddle 示例

              【讨论】:

              • 为什么大家都坚持innerHTML???使用 .text !以及为什么将所有这些东西传递给函数。只需传递(this)并让函数决定使用什么
              • 嗯,我认为它可能会更好/更快,但我想听听@mplungjan 的反驳。
              • innerHTML 是微软发明的一种便捷方法。然后将其复制到更多浏览器,但从a)不是标准,b)您不能在一个选项中拥有html,绝对不需要在选项具有.value和.text span>时混淆问题。
              • innerHTML 非常方便,但我愿意为此牺牲所有的标准和简单性。 :P
              • 我个人将 .text() 与 jQuery 一起使用,将 .innerHTML 与纯 JS 一起使用,这有助于我在混合框架时避免错误,这只是出于习惯。我知道 innerHTML 适用于所有浏览器,这让我很高兴 :) 哦,我指定了两个函数参数,以便 OP 可以更轻松地与我的解决方案相关联,没有其他原因。
              【解决方案15】:

              您可以使用getSelected() 方法获取包含所选项目的类数组对象。像这样:

              querySelector('#box1').getSelected()
              

              因此您可以提取带有.textContent 属性的文本。像这样:

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

              如果你有一个多选框,你可以循环遍历类似数组的对象 希望对你有帮助??

              【讨论】:

                猜你喜欢
                • 2011-06-06
                • 2013-02-05
                • 2023-01-11
                • 2015-05-28
                • 1970-01-01
                • 2015-07-30
                相关资源
                最近更新 更多