Tarleton Dewé
Tarleton Dewé

Reputation: 49

HTML form show fields depending on drop down selected

Having an issue here. Trying to make certain fields appear depending on what has been selected in a drop down box. I"ve had a look on stack and have tried editing the code here: http://jsfiddle.net/tarleton/p8ARq/15/ to work with mine. I cannot seem to get it to work...total newbie here so any help appreciated.

$("select").change(function () {
    // hide all optional elements
    $('.optional').css('display','none');

    $("select option:selected").each(function () {
        if($(this).name() == "test") {
            $('.test').css('display','block');
        } else if($(this).val() == "test2") {
            $('.test2').css('display','block');
        }
    });
});

HTML:

<form class="contact" name="contact" action="#" method="post">
       <div id="styled-select">
           <select>
            <option name="test" value="Option 1" >Referral</option>
              <option name="test2"value="Option 2">Other</option>
              </select>
       </div>
          <input class="optional test" name="revealtest" style="display:none;" class="hidden-txt">

       <input class="optional other" name="revealtest2" value="" style="display:none;" class="hidden-txt">

</form>

Upvotes: 3

Views: 2670

Answers (3)

Phong Vo
Phong Vo

Reputation: 1078

You can use jQuery to hide all your controls by using $("your_control").hide() or $("your_control").show(), I just update your sample at jsFiddle

Upvotes: 0

Cody Guldner
Cody Guldner

Reputation: 2886

This is the solution that I came up with http://jsfiddle.net/burn123/p8ARq/34/

The major thing that I noticed was that you had style="display:hide". Because this it is an inline style, it won't be easily removed. You also had an unnecessary optional class that added a second display:none to the element. So I removed both of those and set the CSS to

.other, .referral {
  display:none;
}

So the display was only toggled once. Your jQuery was fine for the most part. You needed to have the referral set to $(this).val() like you did for other. Also, you need an ending else if you want the textboxes to hide when you choose something else. I used fadeToggle instead of css("display", "block") to give it a little bit of transition as well. There is probably a more code effective way of accomplishing this, but I'm still pretty new to jquery ;)

Hope this helped

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

There is not .name for jQuery.

You can use .attr()

if($(this).attr('name')

and class can be applied to div or other tag.

so specify what to select as below,

$('input.test2').css('display','block'); 
$('input.test').css('display','block');

Also wrap all class inside single class attribute and also remove inline style because in jQuery you are also doing hiding using .hide().

Upvotes: 1

Related Questions