使用JavaScript在下拉列表中获取选定的值?

Fir*_*and 1660 javascript html-select

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

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

var as = document.form1.ddlViewBy.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 2766

如果你有一个如下所示的select元素:

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>
Run Code Online (Sandbox Code Playgroud)

运行此代码:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Run Code Online (Sandbox Code Playgroud)

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

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
Run Code Online (Sandbox Code Playgroud)

哪个会strUser成为test2

  • `var strUser = e.options [e.selectedIndex] .value;`为什么不只是`var strUser = e.value?` (128认同)
  • @ TheRedPea - 也许是因为当写这个答案时,有一个机会(无论多么遥远)需要容纳古老版本的Netscape Navigator,因此使用了同样古老的方法来访问单个选择的值.但我只是在猜测.;-) (15认同)
  • @ R11G,使用`onchange` :) (11认同)
  • 我这样使用:`var e = document.getElementById("ddlViewBy").value;` (10认同)
  • 它如何适用于多个选择? (9认同)
  • 应该是`e.target.options[e.target.selectedIndex].text` 不知道为什么这里的所有答案都是错误的.. (4认同)
  • @OZZIE - 查看OP问题中以“var e”开头的赋值语句。虽然约定用“e”(或“event”)来表示“eventObject”,但这里 OP 使用它来表示元素。 (2认同)
  • @Salam 那是 jQuery,而不是普通的 JavaScript。 (2认同)

Vit*_*nko 348

普通的JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
Run Code Online (Sandbox Code Playgroud)

jQuery的:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId :selected").val(); // The value of the selected option
Run Code Online (Sandbox Code Playgroud)

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'
}];
Run Code Online (Sandbox Code Playgroud)

  • 这确实以不同的方式对我有用.$("#ddlViewBy:selected").val()没有选中 (6认同)
  • 我一定是做错了什么,因为当我尝试这个时,我会返回下拉菜单中每个选项的文本。 (2认同)
  • `element.options[e.selectedIndex].value` 必须是 `element.options[element.selectedIndex].value` (2认同)

Gre*_*reg 169

var strUser = e.options[e.selectedIndex].value;
Run Code Online (Sandbox Code Playgroud)

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

var strUser = e.options[e.selectedIndex].text;
Run Code Online (Sandbox Code Playgroud)

所以你对术语很清楚:

<select>
    <option value="hello">Hello World</option>
</select>
Run Code Online (Sandbox Code Playgroud)

此选项包括:

  • 指数= 0
  • 值=你好
  • Text = Hello World


Cod*_*Spy 59

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

来源链接

工作演示

 <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()">
Run Code Online (Sandbox Code Playgroud)

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

<script>
    function run() {
        document.getElementById("srt").value = document.getElementById("Ultra").value;
    }
</script>
Run Code Online (Sandbox Code Playgroud)

以下脚本从文本框2获取值并使用其值进行警报

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

以下脚本从函数调用函数

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

    function pop(val) {
        alert(val);
    }?
</script>
Run Code Online (Sandbox Code Playgroud)


Moh*_*sal 36

var selectedValue = document.getElementById("ddlViewBy").value;
Run Code Online (Sandbox Code Playgroud)

  • 这是最简单的解决方案,至少对于现代浏览器而言.另请参阅[W3Schools](https://www.w3schools.com/jsref/prop_select_value.asp). (3认同)

Car*_*ger 20

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

var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;
Run Code Online (Sandbox Code Playgroud)

在Firefox等人中运行上面的内容会给你一个'不是函数'的错误,因为IE允许你使用()而不是[]来逃避:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Run Code Online (Sandbox Code Playgroud)

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


boa*_*eng 15

<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>
Run Code Online (Sandbox Code Playgroud)


Ola*_*ran 15

我不确定我是否完全理解你的问题,但这对我有用:

例如,在 HTML 中使用 onchange() 事件。

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

JavaScript

function selectNum() {
    var strUser = document.getElementById("numberToSelect").value;
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供每次点击选择下拉菜单中的任何值。


小智 12

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

所以,我正在getElementByName()为新开发人员添加解决方案.

NB.表单元素的名称必须是唯一的,表单一旦发布就可以使用,但DOM可以允许名称由多个元素共享.因此,如果可以,请考虑向表单添加ID,或者明确表单元素名称my_nth_select_named_xmy_nth_text_input_named_y.

示例使用getElementByName:

var e = document.getElementByName("my_select_with_name_ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Run Code Online (Sandbox Code Playgroud)


小智 11

只是用

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

  • $('#SelectBoxId').val(); 获取所选索引值

  • 这使用jQuery,它不回答OP的问题. (5认同)

Fra*_*ijn 8

由于可能性,代码的直观性以及id对比的使用,之前的答案仍然留有改进的余地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>
Run Code Online (Sandbox Code Playgroud)

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

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


Dul*_*sta 8

有两种方法可以使用__CODE__或完成此操作__CODE__.

JavaScript的:

var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;

alert (getValue); // This will output the value selected.
Run Code Online (Sandbox Code Playgroud)

要么

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
Run Code Online (Sandbox Code Playgroud)

JQuery的:

$("#ddlViewBy:selected").text(); // Text of the selected value

$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'
Run Code Online (Sandbox Code Playgroud)


小智 7

请参阅使用JavaScript或jQuery选择下拉元素一文.他们使用JavaScript和jQuery以多种方式解释了它.

使用jQuery:

$('select').val();
Run Code Online (Sandbox Code Playgroud)


Cla*_*Luz 7

The simplest way to do this is:

var value = document.getElementById("selectId").value;
Run Code Online (Sandbox Code Playgroud)

  • 好答案!很有用 (2认同)

Ezr*_*ton 7

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

例如:

document.getElementById("ddlViewBy").value;
Run Code Online (Sandbox Code Playgroud)

这不是一种DRY方法

DRY(三行代码):

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

获取第一个选择选项:

console.log(e.target[0]); /* Output: <option value="value_hello">Hello innerText</option>*/
Run Code Online (Sandbox Code Playgroud)

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

e.target[e.target.options.selectedIndex].innerText;
Run Code Online (Sandbox Code Playgroud)

演示

document.getElementById("ddlViewBy").value;
Run Code Online (Sandbox Code Playgroud)
function handleChange(e) {
  let innerText = e.target[e.target.options.selectedIndex].innerText;
  let value = e.target.value;
  /* Do something with these values */
}
Run Code Online (Sandbox Code Playgroud)


Ani*_*non 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);
Run Code Online (Sandbox Code Playgroud)
<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2">test2</option>
  <option value="3"  selected="selected">test3</option>
</select>
Run Code Online (Sandbox Code Playgroud)

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


Gen*_*nko 5

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

let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text
Run Code Online (Sandbox Code Playgroud)

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

let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;
Run Code Online (Sandbox Code Playgroud)

我怀疑这比两行版本更快。我只是喜欢尽可能地整合我的代码。

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


Rou*_*ica 5

你可以用querySelector.

例如

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

var myValue = myElement.querySelector('[selected]').value;
Run Code Online (Sandbox Code Playgroud)


Jwo*_*Ker 5

另一个解决方案是:

document.getElementById('elementId').selectedOptions[0].value
Run Code Online (Sandbox Code Playgroud)


Tho*_*Ace 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>
Run Code Online (Sandbox Code Playgroud)


Her*_*key 5

在更现代的浏览器中,允许我们使用伪类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");
Run Code Online (Sandbox Code Playgroud)
<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>
Run Code Online (Sandbox Code Playgroud)