0

「国」と「州」という名前の 2 つのドロップダウンがあります。「国」ドロップダウンには、インドとパキスタンの 2 つの値があります。「インド」を選択した場合、2 番目のドロップダウン「州」を有効にする必要がありますが、「パキスタン」を選択した場合、2 番目のドロップダウンを無効にする必要があります。jquery を使用してこれを行いたいです。前もって感謝します。

4

2 に答える 2

2

この問題は、次のように分類できます。

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>

このコードを書くには、もっと「エレガント」で「最適化された」方法がありますが、このような問題に誰が取り組むべきかを学んでいる人にとっては、上記の方法が最も読みやすいと思います。

于 2012-07-05T20:47:48.493 に答える
1
$country.change(function(){
  $state.prop('disabled', true)
  if (/india/i.test($(this).val()))
    $state.prop('disabled', false)
})
于 2012-07-05T20:40:31.570 に答える