使用 jquery 禁用特定条件的下拉列表

Disabling dropdown for a certain condition using jquery

本文关键字:下拉列表 特定条件 jquery 使用      更新时间:2023-09-26

>我有两个下拉列表,分别以"国家"和"州"命名。"国家/地区"下拉列表中有两个值,印度和巴基斯坦。如果我选择"印度",那么我的第二个下拉列表"国家"应该启用,但如果我选择"巴基斯坦",那么我的第二个下拉菜单应该被禁用。我想使用 jquery 来做到这一点。提前谢谢。

此问题可以分为以下几类:

If the country is changed, do the following:
   Determine if the country is India. If it is, enable the state dropdown
      or, if the country is not India, disable the state dropdown

用代码编写,它将是:

<select id="country">
  <option value="india">India</option>
  <option value="pakistan">Pakistan</option>
</select>
<select id="state">
   <option value="1">State 1</option>
   <option value="2">State 2</option>
   <option value="3">State 2</option>
</select>
<script language="javascript">
$(document).ready(function() {
    $("#country").change(function() { // The country value has been changed
          if($(this).val() == 'india') { // The country is set to india
              $("#state").prop('disabled', false); // Since the country is India, enable the state dropdown
          } else { // The country is NOT India
              $("#state").prop('disabled', true); // Since the country is NOT India, so disable the state dropdown
          }
      }
});
</script>

编写此代码的方法更"优雅"和"优化",但我认为对于刚刚学习谁来解决此类问题的人来说,以上是最清晰的。

$country.change(function(){
  $state.prop('disabled', true)
  if (/india/i.test($(this).val()))
    $state.prop('disabled', false)
})