2142

如何使用 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>

4

29 回答 29

3413

如果您有一个如下所示的选择元素:

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

这将strUsertest2

于 2009-07-06T07:29:43.937 回答
431

纯 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'
}];
于 2011-12-18T02:08:16.053 回答
191
var strUser = e.options[e.selectedIndex].value;

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

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

所以你对术语很清楚:

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

此选项具有:

  • 索引 = 0
  • 价值=你好
  • 文本 = 你好世界
于 2009-07-06T07:29:56.760 回答
68

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

来源链接

工作Javascript 和 jQuery 演示

在此处输入图像描述

在此处输入图像描述

 <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>
于 2012-12-03T06:50:20.453 回答
51
var selectedValue = document.getElementById("ddlViewBy").value;
于 2013-10-25T13:27:13.393 回答
26

如果您曾经遇到过纯粹为 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;

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

于 2012-06-18T15:28:28.393 回答
20
<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 树中定位表单然后在表单中定位该元素的需要。

于 2015-04-14T13:45:09.157 回答
18

初学者可能希望从带有 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;
于 2011-03-09T03:32:02.427 回答
17

有两种方法可以使用 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'
于 2018-07-23T13:18:45.837 回答
14

只需使用

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

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

于 2014-02-18T11:01:56.353 回答
12

我不知道我是不是没有正确回答问题的人,但这对我有用:在您的 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;
}

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

于 2020-01-29T13:23:06.427 回答
9

id由于可能性、代码的直观性以及vs的使用,之前的答案仍有改进的空间name。可以读取所选选项的三个数据——它的索引号、它的值和它的文本。这个简单的跨浏览器代码完成了所有三个操作:

<!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 将接受所有地方的圆形。

于 2015-05-22T02:42:35.070 回答
9

使用 jQuery:

$('select').val();
于 2016-05-25T18:42:18.550 回答
8

另一种解决方案是:

document.getElementById('elementId').selectedOptions[0].value
于 2018-07-18T18:49:01.460 回答
7

最简单的方法是:

var value = document.getElementById("selectId").value;
于 2020-04-01T12:34:04.977 回答
6

它如何工作的运行示例:

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

于 2017-08-02T13:19:01.410 回答
5

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

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

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

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

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

不幸的是,这仍然会两次获取元素,这并不理想。只抓取一次元素的方法会更有用,但我还没有想出来,关于用一行代码来做这件事。

于 2017-05-12T16:25:32.073 回答
5

您可以使用querySelector.

例如

var myElement = document.getElementById('ddlViewBy');

var myValue = myElement.querySelector('[selected]').value;
于 2018-01-04T22:36:47.120 回答
5

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

<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>
于 2018-10-12T11:39:03.130 回答
4

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

e. 选项.selectedIndex

于 2015-10-22T22:38:14.647 回答
4

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

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>

于 2020-06-08T20:50:35.783 回答
3

这是一段 JavaScript 代码行:

var x = document.form1.list.value;

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

于 2017-02-27T21:04:55.333 回答
3

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

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

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

于 2020-01-16T23:39:11.117 回答
3

event.target.value在 onChange 回调中为我做了诀窍。

于 2021-04-22T03:50:59.243 回答
2

尝试

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>

于 2019-12-18T20:19:24.827 回答
2

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

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

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

于 2020-07-20T20:06:03.100 回答
1

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

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

于 2014-04-16T20:52:40.230 回答
0

做就是了:document.getElementById('idselect').options.selectedIndex

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

于 2018-12-22T15:03:05.117 回答
-1

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

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

我有点搞笑。这是代码片段:

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

是的,片段有效

于 2020-05-20T08:49:05.133 回答