Search code examples
jqueryhtml-selectshow-hide

Show a text-box when selecting one color and hide other same time


I am having an issue getting the second text-box to hide when selecting the first one. and vice a versa. I think I may not have the code written correctly.

  <select id = 'color2' name = 'dept' onchange = "

            if ($('#color2').val() == 'others')
                    {
                      $('#color_a').show();
                      $('#color_b').hide();
                    } 

            else($('#color2').val() == 'blue')
                    {
                      $('#color_b').show();

                      $('color_a').hide();
                    } 

                   ">


  <option value="">Select a Field</option>
  <option value="blue">BLUE</option>
  <option value="others">others</option>
</select>

Solution

  • Define your element selections on top and assign them to a var, that way you don't have to traverse the DOM every time you click on the element to select the other elements.

    Put it in a script tag, it will save a lot of headaches.

    (function($){
     $(function(){
       var select = $('#color2'),
           colorA = $('#color_a'),
           colorB = $('#color_b');
       
       // hide all colors
       $('.color').hide();
       
       select.on('change', function(){
         $('.color').hide();
         
         if (select.val() == 'others'){
           colorA.show();
         }
         else if (select.val() == 'blue') {
           colorB.show();
         }
         
       });
       
     })
    })(jQuery)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <select id="color2" name='dept'>
      <option value="">Select a Field</option>
      <option value="blue">BLUE</option>
      <option value="others">others</option>
    </select>
    
    <div id="color_a" class="color">Color A (others)</div>
    <div id="color_b" class="color">Color B (blue)</div>