I am using the http://geoplugin.net plugin to detect the users location. I have a <select> with a list of states, and using the jQuery
$.getJSON(url, function(data){
var state = data['geoplugin_region'];
$('#states').val(state).attr('selected',true);
var selectId = "#" + state ;
var citySelect = selectId + "-cities";
$(citySelect).show();
});
Then it uses another plugin I wrote to display the correct select that has the cities for that state. My format for this is the select id is WA-cities for Washington.
Then I wrote this:
var detectedCity = data['geoplugin_city'];
var city = detectedCity.replace(" ","-");
var selectedCity = city.toLowerCase();
var stateDash = state + "-";
var selectedValue = stateDash + selectedCity;
$(citySelect).val(selectedValue).attr('selected',true);
but when a city that isn’t in the select is detected, it just returns the first value. How can I check if that city is in the select and then only select it if it’s there. My select is setup like this (for Washington):
<select name="cities" id="WA-cities" class="cities">
<option value="" selected="selected" disabled>Select a City</option>
<option value="WA-bellingham">Bellingham</option>
<option value="WA-seattle">Seattle</option>
</select>
There are actually more cities in the select. But I’m detected in Mercer Island, which isn’t on the select. the JavaScript says $(citySelect).val('WA-mercer-island).attr('selected',true); but just chooses the Bellingham one because there’s no Mercer Island. What should I do?
This doesn’t mean “Set the option which value = selectedValue”. It’s wrong.
This is the right way,
here is a jsFiddle Example