You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IP定位脚本执行后下拉框选中值丢失,需设置默认选中项

Fixing the Country Dropdown Default Selection Issue

Got it, let's sort out this problem where your dropdown goes blank when the IP's country isn't in your 7 options. The issue right now is that when response.country doesn't match any of your option values, jQuery's val() sets the select to an empty value, overriding the default selected Belize option.

Here's the adjusted script that checks if the country code exists in your dropdown first—if it does, select it; if not, stick with Belize as the default:

$.get("http://ipinfo.io", function (response) {
  const $countrySelect = $('.country');
  // Check if an option with the returned country code exists
  if ($countrySelect.find(`option[value="${response.country}"]`).length > 0) {
    $countrySelect.val(response.country);
  } else {
    // Fallback to Belize (BZ) if no match
    $countrySelect.val('BZ');
  }
}, "jsonp");

Full Working Code Example

<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>

<script>
$.get("http://ipinfo.io", function (response) {
  const $countrySelect = $('.country');
  if ($countrySelect.find(`option[value="${response.country}"]`).length > 0) {
    $countrySelect.val(response.country);
  } else {
    $countrySelect.val('BZ');
  }
}, "jsonp");
</script>

Quick Notes:

  • We first store the select element in a variable ($countrySelect) to avoid re-querying the DOM multiple times—this is a small performance win.
  • Using find() to check if the option exists ensures we only set the value if it's a valid option.
  • You don't need the .attr('selected',true) call anymore—jQuery's val() method automatically handles setting the selected state for valid options.

内容的提问来源于stack exchange,提问作者Alejandro Hdz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:38:08