doremi
doremi

Reputation: 15339

jQuery - Reuse variable in a select

Say I have:

HTML:

<select id="mySelect"><option value="0">option-1</option>...</select>

JS:

var select = $("#mySelect");

and I further down, I want to do:

var val = $("#mySelect option:selected").val();

I've tried this, but it seems to only return the text, not the value attribute:

$(select + "option:selected").val();
$(select + "option:selected").attr("value"); // also doesn't work

Upvotes: 2

Views: 726

Answers (3)

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15369

Try this:

var strSelect = "#mySelect";
var val = $(strSelect + " option:selected").val();

Upvotes: 0

ChristopheCVB
ChristopheCVB

Reputation: 7305

Try

$(select).find("option:selected").val();

Upvotes: 0

Narnian
Narnian

Reputation: 3908

Try the .find() method.

var opt = $("#mySelect");

var val = opt.find("option:selected").val();

(just couldn't use "select" since it's reserved in so many languages)

This may be a little more efficient since you're not doing a new find each time.

Upvotes: 4

Related Questions