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?
splitreturns 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 likesplit(':').shift()would be a better option? And using some data attributes to identify the options would be even better.