Alejandro Hdz
Alejandro Hdz

Reputation: 81

Selected value in dropdown lost after location script

I have this code that selects the country in a dropdown (that only contains 7 countries) through visitor IP, problem is that when a country is not found as an option the dropdown ignores any default selected values and just shows a blank space. I want to have a default selected value (in this case Belize) after the script is run.

Here is the script:

$.get("http://ipinfo.io", function (response) {
    $('.country').val(response.country).attr('selected',true);
  }, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="country">
  <option value="BZ" selected>Belize</option>
  <option value="GT">Guatemala</option>
  <option value="HN">Honduras</option>
  <option value="SV">El Salvador</option>
  <option value="NI">Nicaragua</option>
  <option value="CR">Costa Rica</option>
  <option value="PA">Panama</option>
</select>

Thanks.

Upvotes: 0

Views: 21

Answers (1)

Vineesh
Vineesh

Reputation: 3782

You can add a condition to check if the country is present in the select options

$.get("http://ipinfo.io", function (response) {
    if($(".country option[value='"+response.country+"']").length > 0){
        $('.country').val(response.country).attr('selected',true);
    }
  }, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="country">
  <option value="BZ" selected>Belize</option>
  <option value="GT">Guatemala</option>
  <option value="HN">Honduras</option>
  <option value="SV">El Salvador</option>
  <option value="NI">Nicaragua</option>
  <option value="CR">Costa Rica</option>
  <option value="PA">Panama</option>
</select>

Upvotes: 1

Related Questions