himanshu mishra
himanshu mishra

Reputation: 31

Disabling dropdown for a certain condition using jquery

I have two drop down named with "Country" and "State". There are two values in "Country" drop down, India and Pakistan. If I Select "India" then my second drop down "State" should be enable but if i select "Pakistan" then my second drop down should be disabled.I want to do this using jquery. Thanks in advance.

Upvotes: 0

Views: 1073

Answers (2)

user396404
user396404

Reputation: 2819

This problem can be broken down into the following:

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

Written in code, it would be:

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

There are more "elegant" and "optimized" ways to write this code, but I think the above is most legible for a person just learning who to tackle problems like this.

Upvotes: 2

elclanrs
elclanrs

Reputation: 94131

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

Upvotes: 1

Related Questions