【问题标题】:Retrieving the text of the selected <option> in <select> element在 <select> 元素中检索所选 <option> 的文本
【发布时间】:2010-10-11 06:05:21
【问题描述】:

如下:

<select id="test">
    <option value="1">Test One</option>
    <option value="2">Test Two</option>
</select>

如何使用 JavaScript 获取所选选项(即“测试一”或“测试二”)的文本

document.getElementsById('test').selectedValue 返回 1 或 2,什么属性返回所选选项的文本?

【问题讨论】:

    标签: javascript html dom


    【解决方案1】:

    这很简单。在 javascript 中,任何带有 ID 的东西都不需要 document.queryselector$('#test') 你可以使用 test.然后,您只需遍历 javascript 中的 selectedOptions 即可,您可以将其添加到新数组中,并以您想要的方式使用该数据。

    let selectedItems = [];
    for ( var i = 0; i < test.selectedOptions.length; i++) {
        selectedItems.push(test.selectedOptions[i].text);
    }
    

    还有

    // if you want values
    selectedItems.push(test.selectedOptions[i].value);
    

    【讨论】:

      【解决方案2】:

      :checked 选择器可以与document.querySelector 一起使用来检索选定的选项。

      let selectedText = document.querySelector('#selectId option:checked').text;
      // or
      let selectedText = document.querySelector('#selectId')
            .querySelector('option:checked').text;
      

      document.querySelector('button').addEventListener('click', function(e) {
        console.log(document.querySelector('#selectId option:checked').text);
      });
      <select id="selectId">
        <option>a</option>
        <option>b</option>
        <option>c</option>
      </select>
      <button>
      Get selected text
      </button>

      对于带有multiple属性的select元素,document.querySelectorAll可以用来获取所有选中的选项。

      let selectedText = [...document.querySelectorAll('#selectId option:checked')]
         .map(o => o.text);
      

      document.querySelector('button').addEventListener('click', function(e) {
        let selectedText = [...document.querySelectorAll('#selectId option:checked')]
                            .map(o => o.text);
        console.log(selectedText);
      });
      <select id="selectId" multiple>
        <option>a</option>
        <option>b</option>
        <option>c</option>
      </select>
      <button>
      Get selected text
      </button>

      【讨论】:

        【解决方案3】:
        function getSelectedText(elementId) {
            var elt = document.getElementById(elementId);
        
            if (elt.selectedIndex == -1)
                return null;
        
            return elt.options[elt.selectedIndex].text;
        }
        
        var text = getSelectedText('test');
        

        【讨论】:

        • 一如既往的出色 javascript!
        • 此答案已过时,请参阅下面的@davidjb 的答案以获得不错的 HTML5 单线。
        • @Christallkeks - 单线throws an exception if nothing is selected。行数越少并不总是越好。
        【解决方案4】:

        简单的方法:

        const select = document.getElementById('selectID');
        const selectedOption = [...select.options].find(option => option.selected).text;
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        • 我不明白这有多简单。当您已经知道所选项目的索引时,为什么还要使用find()?另外,如果没有选中项(&lt;select multiple&gt;),这将产生错误。
        【解决方案5】:

        在 HTML5 下你可以这样做:

        document.getElementById('test').selectedOptions[0].text
        

        MDN 在https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions 的文档表明完全支持跨浏览器(至少截至 2017 年 12 月),包括 Chrome、Firefox、Edge 和移动浏览器,但不包括 Internet Explorer。

        【讨论】:

        • +1,同时这是要走的路。 Firefox 票已修复,我什至费心打开 MS Edge 以验证他们是否也支持它。
        【解决方案6】:

        您可以使用selectedIndex 来检索当前选中的option

        el = document.getElementById('elemId')
        selectedText = el.options[el.selectedIndex].text
        

        【讨论】:

          【解决方案7】:

          使用选择列表对象,来标识它自己的选择选项索引。 从那里 - 获取该索引的内部 HTML。 现在您有了该选项的文本字符串。

          <select onchange="alert(this.options[this.selectedIndex].innerHTML);">
                 <option value="">Select Actions</option>
                 <option value="1">Print PDF</option>
                 <option value="2">Send Message</option>
                 <option value="3">Request Review</option>
                 <option value="4">Other Possible Actions</option>
              </select>
          

          【讨论】:

          • 添加一些解释
          • .innerHTML 获取所有孩子及其属性。虽然它在元素没有子元素时有效,但如果您有一个有子元素的元素,它返回的方式比预期的要多。
          • 您希望在 标签之间有多少个“孩子”?
          【解决方案8】:

          this.options[this.selectedIndex].innerText

          【讨论】:

            【解决方案9】:

            如果你找到了这个帖子并想知道如何通过事件获取选定的选项文本,这里是示例代码:

            alert(event.target.options[event.target.selectedIndex].text);
            

            【讨论】:

              【解决方案10】:
              selectElement.options[selectElement.selectedIndex].text;
              

              参考资料:

              【讨论】:

              • 比@wormhit 给出的答案容易理解。 +1 用于简化
              【解决方案11】:

              类似于@artur,只是没有 jQuery,使用纯 javascript:

              // 使用@Sean-bright 的“elt”变量

              var selection=elt.options[elt.selectedIndex].innerHTML;
              

              【讨论】:

                【解决方案12】:
                document.getElementById('test').options[document.getElementById('test').selectedIndex].text;
                

                【讨论】:

                • 在尝试了所有其他选项之后,它也对我有用。
                • 这个词太完美了!
                【解决方案13】:

                如果你使用jQuery,那么你可以编写如下代码:

                $("#selectId option:selected").html();
                

                【讨论】:

                • 既然他想要文字,可能最好用.text()
                • 不要与$("#selectId option[selected]") 混淆,后者将选择具有“selected”属性但当前可能未被选中的选项。
                • 似乎更复杂。!
                【解决方案14】:

                options 属性包含所有&lt;options&gt; - 从那里您可以查看.text

                document.getElementById('test').options[0].text == 'Text One'
                

                【讨论】:

                  猜你喜欢
                  • 2015-08-05
                  • 2013-04-27
                  • 1970-01-01
                  • 2021-10-03
                  • 2013-12-04
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多