2

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
2
  • 1
    You cannot concatenate a jQuery object and a String. Commented Jul 14, 2011 at 17:57
  • That doesn't really answer my question: How I can reuse the object to get the selected option value? Commented Jul 14, 2011 at 17:57

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This works. How efficient is find? Is this the most optimized way?
Find is the most efficient way to do this that I can think of.
From what I've read, it's better to do a single find instead of doing a new find each time, since it has to go through the entire DOM. Going from an object you already have minimizes the search time.
0

Try

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

Comments

0

Try this:

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

3 Comments

It's not just the missing space, the select var is just a string. Narnian has a better solution in use of the .find() method, useful if you need select to actually be a jQuery object (i.e. if you're already performing some operations on it).
Is this space really needed? If so, some of the examples in the jQuery doc are wrong: api.jquery.com/val
Sorry, not sure how the space got in the option:selected part. I was referring to the space before option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.