简体   繁体   中英

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.

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.

Right now I'm using this code but it's not working:

JQUERY

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

However it's not bringing back "1", "2", "3", etc.

When I run console.log(a) I get the following:

控制台日志

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.

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

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

Try this..

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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