How to trigger an event on a select menu item with JQuery

1.2k views Asked by At

A very basic question, I'm sure, that I can't seem to crack. What I would like to do is simply trigger a simple event when a specific option in a select menu is picked.

This is the basic SELECT menu item:

<select id="mySelect">
  <option value=1>1 - Does not show</option>
  <option value=2>2 - Does not show</option>
  <option value=3>3 - Does show</option>
</select>

The item to be targeted by the event:

<div id="see-me-now" style="display:none;">Boo!</div>

The JQuery I've got so far:

$(document).ready(function(){
   $("#mySelect").change(function(){
        $("#see-me-now").fadeIn('slow');
   });
});

Now, I know where I'm missing some code, I just can't seem to get exactly what that code is:

$(document).ready(function(){
   $("#mySelect").change(function(){
      $(*MISSING CODE GOES HERE, I BET*){
        $("#see-me-now").fadeIn('slow');
      });
   });
});

Thanks

2

There are 2 answers

0
Praveen Kumar Purushothaman On

What you have done is completely right. But you forgot to add the condition. See the code below:

$(document).ready(function(){
   $("#mySelect").change(function(){
      if ($(this).val() == 3) {
        $("#see-me-now").fadeIn('slow');
      }
   });
});

And also there's an error in your code. The if condition should have a different closing.

Snippet

$(document).ready(function(){
  $("#mySelect").change(function(){
    if ($(this).val() == 3) {
      $("#see-me-now").fadeIn('slow');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="mySelect">
  <option value=1>1 - Does not show</option>
  <option value=2>2 - Does not show</option>
  <option value=3>3 - Does show</option>
</select>

<div id="see-me-now" style="display:none;">Boo!</div>

2
cari On

you want this?

if($(this).val() == 3) {
    $("#see-me-now").fadeIn('slow');
}