【问题标题】:Get selected value in dropdown list using JavaScript使用 JavaScript 在下拉列表中获取选定值
【发布时间】:2010-11-08 07:39:53
【问题描述】:

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

我尝试了以下方法,但它们都返回选定的索引而不是值:

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

【问题讨论】:

  • 如果不使用 selected 属性,如何获取选定的值?

标签: 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 strUser = e.value;

将使strUser 成为2。如果你真正想要的是test2,那么这样做:

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

这将使strUser 成为test2

【讨论】:

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

jQuery:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId :selected").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 的等效项...
  • 应该是e.target.options[e.target.selectedIndex].text 不知道为什么这里的所有答案都错了..
【解决方案3】:
var strUser = e.options[e.selectedIndex].value;

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

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

所以你对术语很清楚:

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

这个选项有:

  • 索引 = 0
  • 值 = 你好
  • 文本 = Hello World

【讨论】:

  • 我认为 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】:

      初学者可能希望从带有 NAME 属性而不是 ID 属性的选择中访问值。我们知道所有表单元素都需要名称,甚至在它们获得 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[] 的数组则不起作用
      【解决方案9】:

      有两种方法可以使用 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
      

      jQuery:

      $("#ddlViewBy:selected").text(); // Text of the selected value
      
      $("#ddlViewBy").val(); // Outputs the value of the ID in '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;
              

              【讨论】:

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

              运行示例:

              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 更改。

              【讨论】:

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

              您可以使用querySelector

              例如

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

              【讨论】:

                【解决方案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】:

                        这是一段 JavaScript 代码行:

                        var x = document.form1.list.value;
                        

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

                        【讨论】:

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

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

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

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

                        【讨论】:

                          【解决方案24】:

                          event.target.value 在 onChange 回调中为我解决了问题。

                          【讨论】:

                            【解决方案25】:

                            试试

                            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>

                            【讨论】:

                              【解决方案26】:

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

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

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

                              【讨论】:

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

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

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

                              【讨论】:

                              • 说到简单,我想的是 this 而不是 event.target
                              【解决方案28】:

                              只要做:document.getElementById('idselect').options.selectedIndex

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

                              【讨论】:

                                【解决方案29】:

                                制作一个包含多个选项的下拉菜单(任意数量!)

                                <select>
                                  <option value="giveItAName">Give it a name
                                  <option value="bananaShark">Ridiculous animal
                                  <ooption value="Unknown">Give more options!
                                </select>
                                

                                我有点搞笑。 这是sn-p的代码:

                                <select>
                                  <option value="RidiculousObject">Banana Shark
                                  <option value="SuperDuperCoding">select tag and option tag!
                                  <option value="Unknown">Add more tags to add more options!
                                </select>
                                <h1>Only 1 option (Useless)</h1>
                                <select>
                                  <option value="Single">Single Option
                                </select>  

                                是的,sn-p 工作了

                                【讨论】:

                                  猜你喜欢
                                  • 2022-12-10
                                  • 2013-09-21
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2011-01-25
                                  相关资源
                                  最近更新 更多