简体   繁体   English

在更改时从 Select 获取选定的值/文本

[英]Get selected value/text from Select on change

<select onchange="test()" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
</select>

I need to get the value of the selected option in javascript: does anyone know how to get the selected value or text, please tell how to write a function for it.我需要在 javascript 中获取所选选项的值:有谁知道如何获取所选值或文本,请告诉如何为其编写 function。 I have assigned onchange() function to select so what do i do after that?我已将 onchange() function 分配给 select 那么之后我该怎么办?

Use either JavaScript or jQuery for this.为此,请使用 JavaScript 或 jQuery。

Using JavaScript使用 JavaScript

<script>
function val() {
    d = document.getElementById("select_id").value;
    alert(d);
}
</script>

<select onchange="val()" id="select_id">

Using jQuery使用 jQuery

$('#select_id').change(function(){
    alert($(this).val());
})

If you're googling this, and don't want the event listener to be an attribute, use:如果您正在谷歌搜索,并且不希望事件侦听器成为属性,请使用:

 document.getElementById('my-select').addEventListener('change', function() { console.log('You selected: ', this.value); });
 <select id="my-select"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select>

Wow, no really reusable solutions among answers yet.. I mean, a standart event handler should get only an event argument and doesn't have to use ids at all.. I'd use:哇,答案中还没有真正可重用的解决方案。我的意思是,标准事件处理程序应该只获取一个event参数,并且根本不必使用 ids 。我会使用:

function handleSelectChange(event) {

    // if you want to support some really old IEs, add
    // event = event || window.event;

    var selectElement = event.target;

    var value = selectElement.value;
    // to support really old browsers, you may use
    // selectElement.value || selectElement.options[selectElement.selectedIndex].value;
    // like el Dude has suggested

    // do whatever you want with value
}

You may use this handler with each – inline js:您可以将此处理程序与每个内联 js 一起使用:

<select onchange="handleSelectChange(event)">
    <option value="1">one</option>
    <option value="2">two</option>
</select>

jQuery: jQuery:

jQuery('#select_id').on('change',handleSelectChange);

or vanilla JS handler setting:或香草 JS 处理程序设置:

var selector = document.getElementById("select_id");
selector.onchange = handleSelectChange;
// or
selector.addEventListener('change', handleSelectChange);

And don't have to rewrite this for each select element you have.并且不必为您拥有的每个select元素重写它。

Example snippet:示例片段:

 function handleSelectChange(event) { var selectElement = event.target; var value = selectElement.value; alert(value); }
 <select onchange="handleSelectChange(event)"> <option value="1">one</option> <option value="2">two</option> </select>

 function test(a) { var x = (a.value || a.options[a.selectedIndex].value); //crossbrowser solution =) alert(x); }
 <select onchange="test(this)" id="select_id"> <option value="0">-Select-</option> <option value="1">Communication</option> <option value="2">Communication</option> <option value="3">Communication</option> </select>

No need for an onchange function.不需要 onchange 函数。 You can grab the value in one line:您可以在一行中获取值:

document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value;

Or, split it up for better readability:或者,将其拆分以获得更好的可读性:

var select_id = document.getElementById("select_id");

select_id.options[select_id.selectedIndex].value;
let dropdown = document.querySelector('select');
if (dropdown) dropdown.addEventListener('change', function(event) {
    console.log(event.target.value);
});

I wonder that everyone has posted about value and text option to get from <option> and no one suggested label .我想知道每个人都发布了关于从<option>获取的valuetext option 并且没有人建议label

So I am suggesting label too, as supported by all browsers所以我也建议label ,所有浏览器都支持

To get value (same as others suggested)获得value (与其他人建议的相同)

function test(a) {
var x = a.options[a.selectedIndex].value;
alert(x);
}

To get option text (ie Communication or -Select-)获取option text (即通信或-Select-)

function test(a) {
var x = a.options[a.selectedIndex].text;
alert(x);
}

OR (New suggestion)(新建议)

function test(a) {
var x = a.options[a.selectedIndex].label;
alert(x);
}

HTML HTML

<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2" label=‘newText’>Communication</option>
</select>

Note: In above HTML for option value 2, label will return newText instead of Communication注意:在上面的option值 2 的 HTML 中, label将返回newText而不是Communication

Also

Note: It is not possible to set the label property in Firefox (only return).注意:无法在 Firefox 中设置 label 属性(仅返回)。

HTML: HTML:

<select onchange="cityChanged(this.value)">
      <option value="CHICAGO">Chicago</option>
      <option value="NEWYORK">New York</option>
</select>

JS: JS:

function cityChanged(city) {
    alert(city);
}

Use利用

document.getElementById("select_id").selectedIndex

Or to get the value:或获取值:

document.getElementById("select_id").value
<script>
function test(a) {
    var x = a.selectedIndex;
    alert(x);
}
</script>
<select onchange="test(this)" id="select_id">
    <option value="0">-Select-</option>
    <option value="1">Communication</option>
    <option value="2">Communication</option>
    <option value="3">Communication</option>
</select>

in the alert you'll see the INT value of the selected index, treat the selection as an array and you'll get the value在警报中,您将看到所选索引的 INT 值,将所选内容视为数组,您将获得该值

Why overcomplicate it:为什么过于复杂:

var select = document.querySelector('[select#id.orClass]');
select.addEventListener('change', function() {
  console.log(select.value);

  // or if it changes dynamically
  console.log(e.target.value);      
});

 let select = document.getElementById('select_id'); select.addEventListener('change', function() { console.log(select.value); // just for test alert(select.value); });
 <select id="select_id"> <option value="0">-Select-</option> <option value="1">Communication</option> </select>

 $('#select_id').change(function(){ // selected value alert($(this).val()); // selected text alert($(this).find("option:selected").text()); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <select onchange="test()" id="select_id"> <option value="0">-Select-</option> <option value="1">Communication</option> </select>

This is an old question, but I am not sure why people didn't suggest using the event object to retrieve the info instead of searching through the DOM again.这是一个老问题,但我不确定为什么人们不建议使用事件对象来检索信息,而不是再次通过 DOM 搜索。

Simply go through the event object in your function onChange, see example bellow只需通过函数 onChange 中的事件对象,请参见下面的示例

function test() { console.log(event.srcElement.value); }

http://jsfiddle.net/Corsico/3yvh9wc6/5/ http://jsfiddle.net/Corsico/3yvh9wc6/5/

Might be useful to people looking this up today if this wasn't default behavior 7 years ago如果这不是 7 年前的默认行为,可能对今天查找此内容的人有用

 function test(){ var sel1 = document.getElementById("select_id"); var strUser1 = sel1.options[sel1.selectedIndex].value; console.log(strUser1); alert(strUser1); // Inorder to get the Test as value ie "Communication" var sel2 = document.getElementById("select_id"); var strUser2 = sel2.options[sel2.selectedIndex].text; console.log(strUser2); alert(strUser2); }
 <select onchange="test()" id="select_id"> <option value="0">-Select-</option> <option value="1">Communication</option> </select>

 function test(){ var sel1 = document.getElementById("select_id"); var strUser1 = sel1.options[sel1.selectedIndex].value; console.log(strUser1); alert(strUser1); // Inorder to get the Test as value ie "Communication" var sel2 = document.getElementById("select_id"); var strUser2 = sel2.options[sel2.selectedIndex].text; console.log(strUser2); alert(strUser2); }
 <select onchange="test()" id="select_id"> <option value="0">-Select-</option> <option value="1">Communication</option> </select>

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

I have tried to explain with my own sample, but I hope it will help you.我试图用我自己的样本来解释,但我希望它会对你有所帮助。 You don't need onchange="test()" Please run code snippet for getting a live result.您不需要onchange="test()"请运行代码片段以获得实时结果。

 document.getElementById("cars").addEventListener("change", displayCar); function displayCar() { var selected_value = document.getElementById("cars").value; alert(selected_value); }
 <select id="cars"> <option value="bmw">BMW</option> <option value="mercedes">Mercedes</option> <option value="volkswagen">Volkswagen</option> <option value="audi">Audi</option> </select>

You can get it just using plain old easy and simple JavaScript .您只需使用简单而简单的 JavaScript 即可获得它。

 <select onchange="test()" id="select_id">
  <option value="0">-Select-</option>
  <option value="1">Communication</option>
 </select>

 function test()
 {
  let order_details_id=document.getElementById('select_id').value;
  alert(select_id);
 }
You can get the value from the select element by passing "this.value" as
a parameter to your function named test(this.value) and after that
You should create the function with a parameter inside the script element
and finally u can write console.log(number) inside this function to get Your selected value.


<!DOCTYPE html>
    <html>
    <body>
    
    <p>Select a new car from the list.</p>
    <select onchange="test(this.value)" id="select_id">
        <option value="0">-Select-</option>
        <option value="1">Communication</option>
    </select>
    
   
    
    <script>
    function test(number){
    console.log(number)
    }
    
    </script>
    
    </body>
    </html>

In html在 html 中

(change)="onChangeCategory($event)"

In javascript/typescript在 javascript/打字稿中

onChangeCategory(event: any) {
    console.log(event.target.options[event.target.selectedIndex].value);
    console.log(event.target.options[event.target.selectedIndex].text);
}

You set the onchange handler to some function or string.您将 onchange 处理程序设置为一些 function 或字符串。 In it, you write code to get value在其中,您编写代码以获取价值

document.getElementById('cphForm_ddlFacility').value;

or, for older browsers或者,对于旧版浏览器

document.getElementById('cphForm_ddlFacility')[document.getElementById('cphForm_ddlFacility').selectedIndex].value

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

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