4

I am using JQuery to create dynamic dropdown boxes (the selection of the first drop down filters options in the second). I am trying to create a check for a reverse use case (selection of second drop down forces associated selection in the first).

I have previously used this code to successfully set the active value:

$("#department option[value='Other']").prop('selected', true);

Now, I am trying to do the same as above, but by using a variable value instead of a hardcoded one. This is the code I have so far:

var selected_campus = $("#college")[0].options[$("#college")[0].selectedIndex].text.split(":",1).toString();
$("#campus option[value=selected_campus]").prop('selected', true);

The first line works fine and the desired value is successfully stored in selected_campus. However, the second line does not. How can I set the selected value of #campus to selected_campus?

3
  • Note that split returns an array, and you coerce that array to a string. The only reason it works is because you added a limit so you always get a single item in the array, and stringifying that array returns the expected result, hopefully. I would think something like split(':').shift() would be a better option? And using some data attributes to identify the options would be even better. Commented Feb 14, 2017 at 17:34
  • @adeneo Thanks for the feedback. I'm still quite new so I wasn't aware of shift() and it appears to do exactly what I need! Commented Feb 14, 2017 at 17:36
  • That entire line looks iffy, there's probably better ways all together to bind the options together in some sort of system Commented Feb 14, 2017 at 17:37

2 Answers 2

3

You were close; you have just to concatenate the variable selected_campus with the selector (string) using the + and single quotes ' sign, like :

$("#campus option[value='"+selected_campus+"']").prop('selected', true);
________________________^_^_______________^_^

Instead of :

$("#campus option[value=selected_campus]").prop('selected', true);

Hope this helps.

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

Comments

3

You need to substitute the variable into the code:

$("#campus option[value='" + selected_campus + "']").prop('selected', true);

You would need the single quotes in case the value has spaces or other characters in it

Comments

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.