Claudio Delgado
Claudio Delgado

Reputation: 2349

Adding jQuery function to select box to make it change the CSS dynamically

I want my select box to dynamically change the CSS of another part of the page so that the right options are visible according to each selection.

E.g. the right DIV elements are shown when the correlating select option is selected.

My select input and DIVs:

<select id="chooser" class="input_select" name="chooser">
<option value="">Select...</option>
<option value="Car">Car</option>
<option value="House">House</option>
<option value="Commercial">Commercial</option>
<option value="Other">Other</option>
</select>

<div id="car" style="display:none;">Cars</div>
<div id="house" style="display:none;">House related</div>
<div id="commercial" style="display:none;">Commercial stuff</div>
<div id="other" style="display:none;">Other stuff</div>

my jquery so far:

$(document).ready(function() {

$('#chooser').change{
  $('#house').hide()
  $('#commercial').hide()
  $('#other').hide()
  $('#car').show()
}
});

I'm a noob at jQuery and I just don't know HOW to tell it to filter it by which option is selected. I mean, I think I added the .change{} part right but no idea how to filter it.

Any help is appreciated. Thanks

Upvotes: 1

Views: 475

Answers (3)

Sushanth --
Sushanth --

Reputation: 55750

Try this

$(function() {
    $('#chooser').on('change', function() {
        $('div').hide();
        var val = $(this).find('option:selected').val();
        if (val != '') {
            $('#' + val.toLowerCase()).show();
        }
    }).change();
});​

Try this FIDDLE

Upvotes: 1

Ram
Ram

Reputation: 144689

There is a syntax error in your code, you should pass a function for the change event, try the following:

$(document).ready(function() {
   $('#chooser').change(function(){
      var w = this.value.toLowerCase();
      $('div').hide().filter('#'+w).show();
   })
});

http://jsfiddle.net/ss5G9/

Surely hiding all the div elements on the page is not a good idea, you can add classes to your div elements and hide those specific div elements instead.

<div id="car" class='div' style="display:none;">Cars</div>
<div id="house" class='div' style="display:none;">House related</div>
<div id="commercial" class='div' style="display:none;">Commercial stuff</div>
<div id="other" class='div' style="display:none;">Other stuff</div>

$(document).ready(function() {
   $('#chooser').change(function(){
      var w = this.value.toLowerCase();
      $('.div').hide().filter('#'+w).show();
   }).change()
});

Upvotes: 1

Halcyon
Halcyon

Reputation: 57729

$('#chooser').val() will give you the selected value. Then just use if-else or switch.

Upvotes: 1

Related Questions