Steven
Steven

Reputation: 1

How to get a selection option in jQuery

I have a question about jQuery. Let's say I have a dropdown list:

 <select id="Positions" name="PositionType"> 
        <option value="Manager">Manager</option> 
        <option value="Janitor">Janitor</option> 
        <option value="Cook">Cook</option> 
        <option value="Cashier">Cashier</option> 
        <option value="Other">Other</option> 
  </select>

How could I display an alert box when "other" is selected? So far this does not work:

  <script type="text/javascript"> 
      $(document).ready(function(){
          $("#position").change(function(){
              if($("#position option:selected").val() == "other"){
                  alert("hello world");
              }
              else { 

              }
          });
      }); 
  </script> 

Upvotes: 0

Views: 502

Answers (2)

Mike Sherov
Mike Sherov

Reputation: 13427

Two things. First, as others have mentioned, "other" needs to be uppercase as string comparison is case sensitive. Second, you could retrieve the value of a select much easier:

  <script type="text/javascript"> 
      $(document).ready(function(){
          $("#position").change(function(){
              if($(this).val() == "Other"){
                  alert("hello world");
              }
              else { 

              }
          });
      }); 
  </script> 

A select element's value is equal to the value of it's selected option :-)

Upvotes: 2

Yaakov Shoham
Yaakov Shoham

Reputation: 10548

In your script, try "Other" with capital-O.

Upvotes: 0

Related Questions