Kevin Aartsen Kevin Aartsen - 1 month ago 7
CSS Question

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.

Answer

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>