Home > Mobile >  How to hide/show a div id with jQuery when html option select is chosen
How to hide/show a div id with jQuery when html option select is chosen

Time:01-09

I have an html option select with two options:

<select name="subject" id="subject">
   <option value="option1">Option 1</option>
   <option value="option2">Option 2</option>
</select>

I also have a div element with id="human-genome".

<div id="human-genome"></div>

I want to hide this id by default and when option 1 is selected. I want to show this id when option 2 is selected.

Here is my Jquery:

   $(document).ready(function(){
  $("#subject").change(function(){
      if($(this.val() == 'option1'){
          $('#human-genome').hide();
      } else {
          $('#human-genome').show();
      });
   
});

For some reason, the code isn't working. Any suggestions? Thank you in advance!

CodePudding user response:

enter image description here I just noticed a syntax error.

CodePudding user response:

Try use $(this).val() instead of your code please.

$(document).ready(function(){
    $("#subject").change(function(){
    if($(this).val() == 'option1'){
      $('#human-genome').hide();
    } else {
      $('#human-genome').show();
    }});});

CodePudding user response:

There is a syntax error in the code you developed. I edited the code as follows to make it understandable.

enter image description here

$(document).ready(function(){
  $("#subject").change(function(){
    console.log(this.value);
    
    if(this.value == 'option1')
    {
      $('#human-genome').show();
    }
    else
    {
      $('#human-genome').hide();
    }
  });
});
#human-genome{
  margin-left: 100px;
  background-color: red;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="subject" id="subject">
   <option value="option1">Show</option>
   <option value="option2">Hide</option>
</select>

<div id="human-genome">TEST</div>

  •  Tags:  
  • Related