Jonathan Bechtel
Jonathan Bechtel

Reputation: 3607

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:

console log

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.

Upvotes: 0

Views: 92

Answers (3)

Malik Naik
Malik Naik

Reputation: 1502

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>

Upvotes: 0

Kaustav Ray
Kaustav Ray

Reputation: 754

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

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

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

Upvotes: 2

Related Questions