【问题标题】:Get selected value in dropdown list using JavaScript使用 JavaScript 获取下拉列表中的选定值
【发布时间】:2022-12-10 18:17:09
【问题描述】:

如何使用 JavaScript 从下拉列表中获取选定的值?

<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>

【问题讨论】:

    标签: javascript html-select


    【解决方案1】:

    给定一个看起来像这样的选择元素:

    <select id="ddlViewBy">
      <option value="1">test1</option>
      <option value="2" selected="selected">test2</option>
      <option value="3">test3</option>
    </select>
    

    运行这段代码:

    var e = document.getElementById("ddlViewBy");
    var value = e.value;
    var text = e.options[e.selectedIndex].text;
    

    结果是:

    value == 2
    text == "test2"
    

    交互示例:

    var e = document.getElementById("ddlViewBy");
    function onChange() {
      var value = e.value;
      var text = e.options[e.selectedIndex].text;
      console.log(value, text);
    }
    e.onchange = onChange;
    onChange();
    <form>
      <select id="ddlViewBy">
        <option value="1">test1</option>
        <option value="2" selected="selected">test2</option>
        <option value="3">test3</option>
      </select>
    </form>

    【讨论】:

    • var strUser = e.options[e.selectedIndex].value;为什么不只是var strUser = e.value ?
    • @TheRedPea——也许是因为在写这个答案时有可能(无论多么遥远)需要容纳一个古老版本的 Netscape Navigator,所以使用了一个同样古老的方法来访问单个选择的值。但我只是猜测。 ;-)
    • 我是这样用的:var e = document.getElementById("ddlViewBy").value;
    • 应该是e.target.options[e.target.selectedIndex].text不知道为什么这里的所有答案都是错误的..
    • @OZZIE - 查看 OP 问题中以 var e 开头的赋值语句。虽然 e(或 event)代表 eventObject 是惯例,但 OP 在这里使用它来代表元素。
    【解决方案2】:

    纯 JavaScript:

    var e = document.getElementById("elementId");
    var value = e.options[e.selectedIndex].value;
    var text = e.options[e.selectedIndex].text;
    

    查询:

    $("#elementId :selected").text(); // The text content of the selected option
    $("#elementId").val(); // The value of the selected option
    

    AngularJS: (http://jsfiddle.net/qk5wwyct):

    // HTML
    <select ng-model="selectItem" ng-options="item as item.text for item in items">
    </select>
    <p>Text: {{selectItem.text}}</p>
    <p>Value: {{selectItem.value}}</p>
    
    // JavaScript
    $scope.items = [{
      value: 'item_1_id',
      text: 'Item 1'
    }, {
      value: 'item_2_id',
      text: 'Item 2'
    }];
    

    【讨论】:

    • 我一定是做错了什么,因为当我尝试这样做时,我会取回下拉列表中每个选项的文本。
    • 这确实以不同的方式对我有用。 $("#ddlViewBy :selected").val() 不是没有选择
    • element.options[e.selectedIndex].value必须是element.options[element.selectedIndex].value
    • 仍然有用 - 感谢您写出变体/语言!现在,如果我只知道 Office JS API Dropdown 的等价物...
    • 它在 jQuery 中也对我有用,只需简单地输入 $("#elementId").val() 而无需提及 selected
    【解决方案3】:
    var strUser = e.options[e.selectedIndex].value;
    

    这是正确的,应该给你价值。 是你要的文字吗?

    var strUser = e.options[e.selectedIndex].text;
    

    所以你很清楚术语:

    <select>
        <option value="hello">Hello World</option>
    </select>
    

    这个选项有:

    • 索引 = 0
    • 值 = 你好
    • 文本 = 你好世界

    【讨论】:

    • 我认为 javascript 中的“.value”应该为我返回值,但只有“.text”会像 asp.net 中的 .SelectedValue 返回的那样返回。感谢您给出的例子!
    • 是的 - 使选项的值与其实际值相同。更简单——上面的人需要写更多的代码来弥补他最初的模糊。
    • 应该是e.target.options[e.target.selectedIndex].text不知道为什么这里的所有答案都是错误的..
    【解决方案4】:

    以下代码展示了与使用 JavaScript 从输入/选择字段获取/放置值相关的各种示例。

    Source Link

    工作Javascript & jQuery Demo

     <select id="Ultra" onchange="run()">  <!--Call run() function-->
         <option value="0">Select</option>
         <option value="8">text1</option>
         <option value="5">text2</option>
         <option value="4">text3</option>
    </select><br><br>
    TextBox1<br>
    <input type="text" id="srt" placeholder="get value on option select"><br>
    TextBox2<br>
    <input type="text" id="rtt"  placeholder="Write Something !" onkeyup="up()">
    

    以下脚本获取所选选项的值并将其放入文本框 1

    <script>
        function run() {
            document.getElementById("srt").value = document.getElementById("Ultra").value;
        }
    </script>
    

    以下脚本从文本框 2 获取一个值并用它的值发出警报

    <script>
        function up() {
            //if (document.getElementById("srt").value != "") {
                var dop = document.getElementById("srt").value;
            //}
            alert(dop);
        }
    </script>
    

    以下脚本是从一个函数调用一个函数

    <script>
        function up() {
            var dop = document.getElementById("srt").value;
            pop(dop); // Calling function pop
        }
    
        function pop(val) {
            alert(val);
        }?
    </script>
    

    【讨论】:

    • onchange=run(this.value)(this.text) 可能更有利。
    【解决方案5】:
    var selectedValue = document.getElementById("ddlViewBy").value;
    

    【讨论】:

    • 这是最简单的解决方案,至少对于现代浏览器而言是这样。另见W3Schools
    【解决方案6】:

    如果您遇到过纯粹为 Internet Explorer 编写的代码,您可能会看到:

    var e = document.getElementById("ddlViewBy");
    var strUser = e.options(e.selectedIndex).value;
    

    在 Firefox 等中运行上面的代码会给你一个“不是函数”的错误,因为 Internet Explorer 允许你使用 () 而不是 []:

    var e = document.getElementById("ddlViewBy");
    var strUser = e.options[e.selectedIndex].value;
    

    正确的方法是使用方括号。

    【讨论】:

      【解决方案7】:
      <select id="Ultra" onchange="alert(this.value)"> 
       <option value="0">Select</option>
       <option value="8">text1</option>
       <option value="5">text2</option>
       <option value="4">text3</option>
      </select>
      

      当您从元素内部访问任何输入/表单字段时,都可以使用“this”关键字。这消除了在 dom 树中定位表单然后在表单内定位该元素的需要。

      【讨论】:

        【解决方案8】:

        有两种方法可以使用 JavaScript 或 jQuery 完成此操作。

        JavaScript:

        var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;
        
        alert (getValue); // This will output the value selected.
        

        或者

        var ddlViewBy = document.getElementById('ddlViewBy');
        
        var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;
        
        var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;
        
        alert (value); // This will output the value selected
        
        alert (text); // This will output the text of the value selected
        

        查询:

        $("#ddlViewBy:selected").text(); // Text of the selected value
        
        $("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'
        

        【讨论】:

        • 工作得很好。非常感谢。
        【解决方案9】:

        初学者可能希望从带有 NAME 属性而不是 ID 属性的 select 中访问值。我们知道所有表单元素都需要名称,甚至在它们获得 ID 之前。

        因此,我添加了 getElementsByName() 解决方案,仅供新开发人员查看。

        注意。表单元素的名称需要是唯一的,以便您的表单在发布后可用,但 DOM 可以允许多个元素共享一个名称。出于这个原因,请考虑在可能的情况下向表单添加 ID,或者明确使用表单元素名称 my_nth_select_named_xmy_nth_text_input_named_y

        使用getElementsByName 的示例:

        var e = document.getElementsByName("my_select_with_name_ddlViewBy")[0];
        var strUser = e.options[e.selectedIndex].value;
        

        【讨论】:

        • 如果 my_select_with_name_ddlViewBy 是像 my_select_with_name_ddlViewBy[] 这样的数组,则不起作用
        【解决方案10】:

        只需使用

        • $('#SelectBoxId option:selected').text(); 用于获取列出的文本

        • $('#SelectBoxId').val(); 用于获取选定的索引值

        【讨论】:

        • 这使用 jQuery,它不回答 OP 的问题。
        【解决方案11】:

        我不知道我是不是那个没有正确回答问题的人,但这对我有用: 在您的 HTML 中使用 onchange() 事件,例如。

        <select id="numberToSelect" onchange="selectNum()">
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
        </select>
        

        //javascript

        function selectNum(){
            var strUser = document.getElementById("numberToSelect").value;
        }
        

        这将为您提供每次点击选择下拉列表中的任何值

        【讨论】:

          【解决方案12】:

          使用 jQuery:

          $('select').val();
          

          【讨论】:

            【解决方案13】:

            由于可能性、代码的直观性以及 idname 的使用,先前的答案仍有改进的余地。人们可以获得所选选项的三个数据的读数——它的索引号、它的值和它的文本。这个简单的跨浏览器代码完成了所有这三个工作:

            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>Demo GetSelectOptionData</title>
            </head>
            <body>
                <form name="demoForm">
                    <select name="demoSelect" onchange="showData()">
                        <option value="zilch">Select:</option>
                        <option value="A">Option 1</option>
                        <option value="B">Option 2</option>
                        <option value="C">Option 3</option>
                    </select>
                </form>
            
                <p id="firstP">&nbsp;</p>
                <p id="secondP">&nbsp;</p>
                <p id="thirdP">&nbsp;</p>
            
                <script>
                function showData() {
                    var theSelect = demoForm.demoSelect;
                    var firstP = document.getElementById('firstP');
                    var secondP = document.getElementById('secondP');
                    var thirdP = document.getElementById('thirdP');
                    firstP.innerHTML = ('This option's index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
                    secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
                    thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
                }
                 </script>
            </body>
            </html>
            

            现场演示:http://jsbin.com/jiwena/1/edit?html,output

            id 应该用于化妆目的。出于功能形式的目的,name 仍然有效,在 HTML5 中也是如此,并且仍应使用。最后,请注意在某些地方使用方括号和圆括号。如前所述,只有(旧版本的)Internet Explorer 会在所有地方接受圆形。

            【讨论】:

              【解决方案14】:

              另一种解决方案是:

              document.getElementById('elementId').selectedOptions[0].value
              

              【讨论】:

              【解决方案15】:

              最简单的方法是:

              var value = document.getElementById("selectId").value;
              

              【讨论】:

              • 他想要的不是值,而是选择框显示的文本
              • 我认为这是大多数人正在寻找的实际答案。
              • 好答案!这很有用
              • 我真的有点困惑阅读这些 cmets。
              【解决方案16】:

              您可以使用querySelector

              例如。

              var myElement = document.getElementById('ddlViewBy');
              
              var myValue = myElement.querySelector('[selected]').value;
              

              【讨论】:

                【解决方案17】:

                它如何工作的运行示例:

                var e = document.getElementById("ddlViewBy");
                var val1 = e.options[e.selectedIndex].value;
                var txt = e.options[e.selectedIndex].text;
                
                document.write("<br />Selected option Value: "+ val1);
                document.write("<br />Selected option Text: "+ txt);
                <select id="ddlViewBy">
                  <option value="1">test1</option>
                  <option value="2">test2</option>
                  <option value="3"  selected="selected">test3</option>
                </select>

                注意:值不会随着下拉列表的更改而更改,如果您需要该功能,则将实施 onClick 更改。

                【讨论】:

                • 显示使用后如何刷新代码的好答案!
                【解决方案18】:

                我对如何实现这一点有不同的看法。我通常使用以下方法来执行此操作(据我所知,这是一种更简单的方法,适用于所有浏览器):

                <select onChange="functionToCall(this.value);" id="ddlViewBy">
                  <option value="value1">Text one</option>
                  <option value="value2">Text two</option>
                  <option value="value3">Text three</option>
                  <option value="valueN">Text N</option>
                </select>
                

                【讨论】:

                  【解决方案19】:

                  为了与之前的答案一致,这就是我作为单行者的做法。这是为了获取所选选项的实际文本。已经有很好的例子可以获取索引号。 (对于文字,我只是想以这种方式展示)

                  let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text
                  

                  在极少数情况下,您可能需要使用括号,但这种情况很少见。

                  let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;
                  

                  我怀疑这个过程比两行版本更快。我只是想尽可能地合并我的代码。

                  不幸的是,这仍然会获取元素两次,这并不理想。一种只获取元素一次的方法会更有用,但我还没有弄清楚,关于用一行代码来做到这一点。

                  【讨论】:

                    【解决方案20】:

                    2015 年,在Firefox 中,以下内容也有效。

                    e.选项.selectedIndex

                    【讨论】:

                      【解决方案21】:

                      在更现代的浏览器中,querySelector 允许我们使用 :checked pseudo-class 在一条语句中检索选定的选项。从选定的选项中,我们可以收集我们需要的任何信息:

                      const opt = document.querySelector('#ddlViewBy option:checked');
                      // opt is now the selected option, so
                      console.log(opt.value, 'is the selected value');
                      console.log(opt.text, "is the selected option's text");
                      <select id="ddlViewBy">
                        <option value="1">test1</option>
                        <option value="2" selected="selected">test2</option>
                        <option value="3">test3</option>
                      </select>

                      【讨论】:

                        【解决方案22】:

                        event.target.value 在 onChange 回调中对我有用。

                        【讨论】:

                          【解决方案23】:

                          这是一段 JavaScript 代码行:

                          var x = document.form1.list.value;
                          

                          假设名为列表name="list" 的下拉菜单包含在名称属性为name="form1" 的表单中。

                          【讨论】:

                          • OP 说这对他们不起作用:“我尝试了下面的方法,但它们都返回选定的索引而不是值:var as = document.form1.ddlViewBy.value;...”
                          【解决方案24】:

                          您应该使用 querySelector 来实现这一点。这也标准化了从表单元素中获取价值的方式。

                          var dropDownValue = document.querySelector('#ddlViewBy').value;

                          小提琴:https://jsfiddle.net/3t80pubr/

                          【讨论】:

                            【解决方案25】:

                            我认为您可以将事件侦听器附加到选择标签本身,例如:

                            <script>
                              document.addEventListener("DOMContentLoaded", (_) => {
                                document.querySelector("select").addEventListener("change", (e) => {
                                  console.log(e.target.value);
                                });
                              });
                            </script>
                            

                            在这种情况下,您应该确保所有选项都有一个值属性,并且它们不为空。

                            【讨论】:

                            • 很好的答案,谢谢!就我而言,我有两个选择器,但我能够使用“e.srcElement.id”访问选择器 ID
                            【解决方案26】:

                            尝试

                            ddlViewBy.value                      // value
                            
                            ddlViewBy.selectedOptions[0].text    // label
                            

                            console.log( ddlViewBy.value );
                            
                            console.log( ddlViewBy.selectedOptions[0].text );
                            <select id="ddlViewBy">
                              <option value="1">Happy</option>
                              <option value="2">Tree</option>
                              <option value="3"  selected="selected">Friends</option>
                            </select>

                            【讨论】:

                              【解决方案27】:
                              <select name="test" id="test" >
                                  <option value="1" full-name="Apple">A</option>
                                  <option value="2" full-name="Ball">B</option>
                                  <option value="3" full-name="Cat" selected>C</option>
                              </select>
                              
                              var obj  = document.getElementById('test');
                              obj.options[obj.selectedIndex].value;  //3
                              obj.options[obj.selectedIndex].text;   //C
                              obj.options[obj.selectedIndex].getAttribute('full-name'); //Cat
                              obj.options[obj.selectedIndex].selected; //true
                              

                              【讨论】:

                                【解决方案28】:

                                这里的大多数答案都是通过纯文本 JavaScript 选择器获取“this”选择菜单 onchange 的值。

                                例如:

                                document.getElementById("ddlViewBy").value;
                                

                                这是不是干燥的方法。

                                干(3 行代码):

                                function handleChange(e) {
                                  let innerText = e.target[e.target.options.selectedIndex].innerText;
                                  let value = e.target.value;
                                  /* Do something with these values */
                                }
                                

                                获取第一个选择选项:

                                console.log(e.target[0]); /*output: <option value="value_hello">Hello innerText</option>*/
                                

                                考虑到这个想法,我们动态返回“这个”选择选项(selectedIndex):

                                e.target[e.target.options.selectedIndex].innerText;
                                

                                演示

                                let log = document.getElementById('log');
                                
                                function handleChange(e) {
                                  let innerText = e.target[e.target.options.selectedIndex].innerText;
                                  let value = e.target.value;
                                  
                                  log.innerHTML = `<table>
                                    <tr><th>value</th><th>innerText</th></tr>
                                    <tr><td>${value}</td><td>${innerText}</td></tr>
                                  </table>`;
                                
                                }
                                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css">
                                
                                <select id="greet" onchange="handleChange(event)">
                                  <option value="value_hello">Hello innerText</option>
                                  <option value="value_goodbye">Goodbye innerText</option>
                                  <option value="value_seeYou">See you... innerText</option>
                                </select>
                                
                                <select id="other_select_menu" onchange="handleChange(event)">
                                  <option value="value_paris">Paris innerText</option>
                                  <option value="value_ny">New York innerText</option>
                                </select>
                                
                                <div id="log"></div>

                                【讨论】:

                                • 有 DRY 和冗长让你的代码更容易理解。在这种情况下,我觉得这个答案在多个层面上增加了复杂性。
                                【解决方案29】:

                                这是在 onchange 函数中执行此操作的简单方法:

                                event.target.options[event.target.selectedIndex].dataset.name

                                【讨论】:

                                • 说到简单,我在想这个代替事件目标
                                【解决方案30】:

                                随便做:document.getElementById('idselect').options.selectedIndex

                                然后你会得到选择索引值,从 0 开始。

                                【讨论】:

                                  猜你喜欢
                                  • 2010-11-08
                                  • 2013-09-21
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2011-01-25
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多