Kevin
Kevin

Reputation: 928

Show hidden field on option click

I have a form inside this form i have a select tag with multiple options check it out:

<select class="form-control" name="footerLayout">
    <option value="1">1 column</option>
</select>

What I'm trying to achieve is when i click on a certain field a certain div will show. In this case if i click on field one it should show me the hidden div.

Look how i tried it:

$('[name=footerLayout]').click(function() {
    $(".column-1").toggle("slow");
});

when I click on footerLayout option 1 it should show me the .column-1 class which is hidden. I know this is wrong but this is what i got so far.

If anyone could point me in the right direction that'd be awesome.

Upvotes: 0

Views: 102

Answers (2)

Abdelaziz Mokhnache
Abdelaziz Mokhnache

Reputation: 4349

you can do it like so, It shows the corresponding div when clicking on the appropriate option:

    <style>
        div {
            display: none;
        }
    </style>

    <select class="form-control" name="footerLayout">
        <option value="1">1 column</option>
        <option value="2">2 column</option>
        <option value="3">3 column</option>
    </select>

    <div class="div1">div 1</div>
    <div class="div2">div 2</div>
    <div class="div3">div 3</div>

    <script src="js/jquery.min.js"></script>
    <script>
        $("option").click(function(){
            var num = $(this).val();
            $('.div' + num).show();
        });
    </script>

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can get the selected value as using .val(), create a valid selector by string concatenation and use perform the desired operation. As you need to display the hidden div, you need to use .show()

$('[name=footerLayout]').change(function() {
    var selector = ".column-" + $(this).val();
    $(selector).show();
});

As per comment in the future i want if you click option 2 to show a hidden div named .column-2

I would recommend, you to use a common class with all the columns like column, then you can use .hide() with Class Selector (“.class”)

$('[name=footerLayout]').change(function() {        
    var selector = ".column-" + $(this).val(); //Create selector        
    $(".column").not(selector).hide(); //Hide others        
    $(selector).show();//Show column based on selected value
});

jQuery(function($) {
  $('[name=footerLayout]').change(function() {
    var selector = ".column-" + $(this).val(); //Create selector        
    $(".column").not(selector).hide(); //Hide others        
    $(selector).show(); //Show column based on selected value
  });
});
.column{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="footerLayout">
  <option value="1">1 column</option>
  <option value="2">2 column</option>
</select>

<div class="column column-1">div 1</div>
<div class="column column-2">div 2</div>

Upvotes: 1

Related Questions