user2694011
user2694011

Reputation:

jQuery show div with same class as selected dropdown value

I have a dropdown:

<select class="select_menu_type">
    <option value="value1">foo</option>
    <option value="value2">bar</option>
</select>

<div class="value1">Lorem ipsum VALUE1</div>
<div class="value2">Lorem ipsum VALUE2</div>

All div's are display none by default. I need to display the div with same class as selected option value.

Any idea how to do this using jQuery?

My progress so far:

jQuery('#select_order_type').change(function(){
  var selectedOption = document.getElementById('select_order_type');
  console.log(selectedOption.options[selectedOption.selectedIndex].value)
});

I need show div with same class as my selected value...

Upvotes: 0

Views: 2379

Answers (3)

wrecklez
wrecklez

Reputation: 347

i already tried it on my own i hope it is the answer for your question :)

First onloading of document we need to get how many options you have in your select and we should hide all the div then show the div that have class equals to the selected value of select box

var optionValues = [];
$('.select_menu_type option').each(function() {
    optionValues.push($(this).val());
});

$( document ).ready(function() {
    for( var ctr = 0; ctr < optionValues.length; ctr++){
        if( $('.select_menu_type').val() === optionValues[ctr]){
            $('.'+optionValues[ctr]).show();
        }
        else{
            $('.'+optionValues[ctr]).hide();
        }
    }
});

then just copy the ready function inside onchange of that select :)

$('.select_menu_type').change(function(){
    for( var ctr = 0; ctr < optionValues.length; ctr++){
        if( $('.select_menu_type').val() === optionValues[ctr]){
            $('.'+optionValues[ctr]).show();
        }
        else{
            $('.'+optionValues[ctr]).hide();
        }
    }
});

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

$(function() {
   $('.select_menu_type').on('change',function() {
        var cls = this.value;
        $('div').hide();
        $('div.' + cls).show();
    });
});

For better coding I would suggest enclosing the div elements in another div or element so that it will be easier to control just those divs.

Upvotes: 0

Wilfredo P
Wilfredo P

Reputation: 4076

You could try:

$('.select_menu_type ').change(function(){
    var $Select = $(this).val();
    $('div').hide();
    $('.'+$Select).show();

})

DEMO

Upvotes: 0

Related Questions