-2

I am trying to use a select/option drop down list so that when you select one of the options other elements are revealed or hidden elsewhere in the page. I have managed to do this with radio buttons using id or class selectors and jquery hide/show functions but can't do it using the select/option drop down list.

Code looks like this:

HTML...

<select name="attending">
  <option id="yes" value="Yes">Yes</option>
  <option id="yes_partner" value="Yes_Partner">Yes + Partner</option>
  <option id="yes_partner_kids" value="Yes_Partner_Kids">Yes + Partner & Kid(s)!!!</option>
  <option id="no" value="No">No</option>
</select>

jquery script...

$(function(){
  $("#yes").click(function(){
      $(".yes").show();
      $(".send").show();
      $(".yes_partner").hide();
      $(".yes_partner_kids").hide();
      $(".main_guest").show();
   });
 });

Have tried with class and id and also tried using jquery select instead of click but no luck. Works with radio buttons but not <option>.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
  • Possible duplicate of [jQuery Get Selected Option From Dropdown](http://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – Wes Foster Jan 11 '16 at 22:42
  • I think you'd be using `.change()` for what you're looking for and using the value of the selected option – ntgCleaner Jan 11 '16 at 22:43

1 Answers1

2

You need to attach a change event to the select and check it's value to make a decision on which items to show / hide.

$(function(){
  $("select[name=attending]").change(function(){     
      if($(this).val() == "yes")
      {
        $(".yes").show();
        $(".send").show();
        $(".yes_partner").hide();
        $(".yes_partner_kids").hide();
        $(".main_guest").show();
      }
   });
 });

The problem with this approach is that you would need a lot of if-else which makes the code convoluted and is hard to managed.

In my opinion, the best thing would be to define the elements you want to hide-show as an attribute to each option element.

 <option id="yes" value="yes" data-show="yes,send,main_guest" data-hide="yes_partner,yes_partner_kids">Yes</option> 

$(function(){
  $("select[name=attending]").change(function(){     
      var itemsToShow = $("#" + $(this).val()).attr("data-show").split(',');
      alert(itemsToShow.length);
      var itemsToHide = $("#" + $(this).val()).attr("data-hide").split(',');
      $.each(itemsToShow,function()
      {
         $('.' + this).show();
      });      
      $.each(itemsToHide,function()
      {
        $('.' + this).hide();
      });      
   });
 });

Here's an example : http://jsfiddle.net/DinoMyte/p8ARq/616/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26