使用 Jquery 设置 Select 选项

Set Select Option Using Jquery

我有国家、州、城市三个 select 框

<select name="property_country" id="country" > 
  <option value="">Country</option>
</select>

<select name="property_state" id="state" > 
  <option value="">State</option>
</select>

<select name="property_city" id="city"> 
  <option value="">City</option>
</select>

PHP 填写国家,Ajax 填写州和城市字段,没有问题。我在数据库中有两个国家 - 印度和美国。

如果我select印度,ajax给出的状态正确。但是,如果我重新 select 选项标签 "Country",那么州和城市字段将变为空白。我需要 jQuery 代码来填充上面给出的默认标签和值 "State" 和 "City" 如果没有国家被 selected(意思是 "Country")是 selected.

这可以通过数据库完成,方法是填写州和城市条目并将它们附加到国家/地区,然后 onload(正文或 javascript)上传默认值。但这将使验证工作也拼凑起来,而不是逻辑流程。因此需要 jQuery 解决方案。

我的jQuery代码如下:

$(document).ready(function() {
  $('#country').on('change', function() {
    var country_id = $('#country').val();
    $.ajax({
      type: 'POST',
      url: '../controllers/select.php',
      data: "country_id=" + country_id,
      success: function(msg) {
        $("#state").html(msg);
      }
    });
  });

  $('#state').on('change', function() {
    var state_id = $('#state').val();
    $.ajax({
      type: 'POST',
      url: '../controllers/select.php',
      data: "state_id=" + state_id,
      success: function(msg) {

        $("#city").html(msg);
      }
    });
  });

我试过了

if (country_id == "") {
    $("#state").val("State");               
} else {    
    $.ajax({});
}

如果重置国家/地区值,您必须再次在 select 字段中添加空白选项。

$('#country').on('change', function() {
var country_id = $('#country').val();
if(country_id){
  $.ajax({
    type: 'POST',
    url: '../controllers/select.php',
    data: "country_id=" + country_id,
    success: function(msg) {
      $("#state").html(msg);
    }
   });
  }
  else{
    $("#state").html(' <option value="">State</option>'); 
    $("#city").html(' <option value="">City</option>'); 
  }
});