简体   繁体   English

用jQuery选择所选元素的选项值

[英]Selecting option value of selected element with jquery

I'm trying to use jquery to select the option value of the selected element in an html dropdown. 我正在尝试使用jquery在html下拉列表中选择所选元素的选项值。

HTML HTML

<select class="select1">
    <option value ="0">" + state.greens[0].name + "</option>
    <option value ="1">" + state.greens[1].name + "</option>
    <option value ="2">" + state.greens[2].name + "</option>
</select>

The option values represent an index position in an array that I can load to generate additional data about objects within them. 选项值表示数组中的索引位置,我可以加载该索引位置以生成有关其中对象的其他数据。

I'm trying to use jquery to grab the option value of whatever dropdown element is currently selected. 我正在尝试使用jquery来获取当前选择的任何下拉元素的选项值。

Right now I'm using this code but it's not working: 现在,我正在使用此代码,但无法正常工作:

JQUERY JQUERY

var a = $(".select1 option:selected");

However it's not bringing back "1", "2", "3", etc. 但是,它不会带回“ 1”,“ 2”,“ 3”等。

When I run console.log(a) I get the following: 当我运行console.log(a)时,我得到以下信息:

控制台日志

Not sure what's happening. 不知道发生了什么。

The idea is that I can use the variable a to load data like state.greens[a].price, state.greens[a].ingredients, etc. 我的想法是我可以使用变量a加载数据,例如state.greens [a] .price,state.greens [a] .ingredients等。

You are almost there. 你快到了。 Just give: 只要给:

var a = $(".select1 option:selected").attr("value");

Or give this: 或者给这个:

var a = $(".select1").val();

You need to get the value of the <select> . 您需要获取<select>的值。

var a = $(".select1").val(); // is the simple solution

Try this.. 尝试这个..

HTML HTML

<select class="select1" id="select1">
    <option value ="0">Option 1</option>
    <option value ="1">Option 2</option>
    <option value ="2">Option 3</option>
</select>

Pure Javascript solution 纯Javascript解决方案

document.getElementById("select1").addEventListener("change", function(){
    var a = document.getElementById("select1").value;

   alert(a);
});

Check out this Fiddle 看看这个小提琴

Snippet 片段

 document.getElementById("select1").addEventListener("change", function(){ var a = document.getElementById("select1").value; alert(a); }); 
 <select class="select1" id="select1"> <option value ="0">Option 1</option> <option value ="1">Option 2</option> <option valuae ="2">Option 3</option> </select> 

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

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