繁体   English   中英

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

[英]Get selected value in dropdown list using JavaScript

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

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

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

<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

纯 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").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'
}];
var strUser = e.options[e.selectedIndex].value;

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

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

所以你对术语很清楚:

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

此选项具有:

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

以下代码展示了与使用 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>
var selectedValue = document.getElementById("ddlViewBy").value;

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

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

<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 树中定位表单然后在表单中定位该元素的需要。

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

初学者可能希望从带有 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;

只需使用

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

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

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

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

由于可能性、代码的直观性以及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 将接受所有地方的圆形。

使用 jQuery:

$('select').val();

另一种解决方案是:

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

您可以使用querySelector

例如

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

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

最简单的方法是:

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

它如何工作的运行示例:

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

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

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

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

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

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

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

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

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

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

e. 选项.selectedIndex

在更现代的浏览器中, 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>

这是一段 JavaScript 代码行:

var x = document.form1.list.value;

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

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

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

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

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

尝试

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>

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

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

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

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

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

我能看到的使该代码不起作用的唯一原因是,如果您使用的是IE7-,并且忘记为<option> -tags指定value属性,则其他所有浏览器都应将open-close标记中的内容转换为期权价值。

只需这样做: document.getElementById('idselect').options.selectedIndex

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

<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

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

例如:

document.getElementById("ddlViewBy").value;

不是DRY 方法。

DRY(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>*/

考虑到这个想法,我们动态返回“this”选择选项项(通过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>

有一个解决方法,使用EasyUI框架及其所有插件

您只需将一些可以从输入中读取的 EasyUI 对象作为“桥梁”添加到下拉菜单中。

示例:easyui-searchbox

左边是下拉菜单,右边是easyui-searchbox:

在此处输入图像描述

...
<input id="ss" class="easyui-searchbox" style="width:300px"
        data-options="  searcher:my_function,
                        prompt:'Enter value',
                        menu:'#mm'">
<div id="mm" style="width:200px">
    <div data-options="name:'1'">test1</div>
    <div data-options="name:'2'">test2</div>
</div>
...
...
<script type="text/javascript">
    function my_js_function(triggeredByButton = false){
        // normal text of the searchbox (what you entered)
        var value = $("#ss").searchbox("getValue");
        // what you chose from the drop-down menu
        var name = $("#ss").searchbox("getName");
...

注意: var name是'1'或'2',即“下拉列表的值”,而var value是在easyui-searchbox中输入的值,如果你只想不相关知道下拉菜单的值。

我检查了 EasyUI 如何获取该#mm名称,但没有 EasyUI 的帮助我无法找到该名称。 getName背后的 jQuery:

getName:function(jq){
return $.data(jq[0],"searchbox").searchbox.find("input.textbox-value").attr("name");
}

注意这个函数返回的不是easyui-searchbox的值,而是作为easyui-searchbox menu参数的#mm下拉菜单的名称。 EasyUI 必须以某种方式获得其他值,因此它必须是可能的。

如果你不想看到任何插件,让它尽可能小? 或者在上面的链接中找到一个根本不需要表单的插件,我只是没有花时间。

我不知道为什么所有答案都会导致很难知道。 我的简单方法是:

var IsActive = $("#yourDropDownList option:selected").val()

您可以以最简单的方式使用IsActive。

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

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

是的,片段有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM