0

I learned that using a reference variable is faster than using $() every line of code (see my previous question): jQuery - Is it okay to use $('#ElementId') everytime?. Now my question is how can I use this reference variable to maximize the power of jQuery? Please see the example below:

Without reference variable:

var ValueOfSelected = $('#SelectElementId option:selected').val();

With reference variable (pseudo-code):

var SelectElement = $('#SelectElementId');
var ValueOfSelected = $(SelectElement).SelectedOption.val();

Note that SelectedOption.val() is the pseudo-code here. Is there such function anyway?

1
  • You don't need to do $(SelectElement) again, you can just use SelectElement directly. Commented Jul 1, 2011 at 3:28

3 Answers 3

2

You can use .find() to find the nested option.

var SelectElement = $('#SelectElementId');
var ValueOfSelected = SelectElement.find('option:selected').val();

...but because it is a select element, you can just use the val()[docs] method directly.

var SelectElement = $('#SelectElementId');
var ValueOfSelected = SelectElement.val();

This will give you the value of the selected option.

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

1 Comment

Ha ha! It's you again! Hey, This is exactly what I'm looking for. Thanks!
1

The result of a JQuery selector, in this case "SelectElement" can be accessed through out the rest of the script. You dont need to use the JQuery Selector "$()" a second time.

Comments

1
var select_element = $('#SelectElementId');
// these two below gives you the same result
var value_of_selected = $('#SelectElementId option:selected').val();
var value_of_selected = select_element.val();

sometimes you don't really have to use reference variables. it's useful if you actually use it multiple times.

2 Comments

You mean, I cannot use my reference variable in jQuery? This time I really need to use a reference variable 'coz I'll be using it for many times.
i've edited my post to show how you can also use the reference variable.

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.