user1009453 user1009453 - 2 months ago 6
jQuery Question

Show/hide content with specific class using jquery

I'am new to jquery and maybe this is a stupid question but I have searched for an answer just about everywhere without finding one. So, here we go:

I want to show different content depending on what option I select in a drop down form. As I have learnt here on StackOverflow, you ca use the change function to do this:

Example:

<script type="text/javascript">

$(document).ready(function() {
$('#myselector').change(function(){
$('.statecontent').hide();
$('#' + $(this).val()).show();
});
});

</script>

<select id="myselector">
<option value="state1"></option><br />
<option value="state2"></option><br />
<option value="state3"></option><br />
</select>

<div id="state1" class="statecontent">State1 Specific Page Content Goes here</div><br />
<div id="state2" class="statecontent">State2 Specific Page Content Goes here</div><br />
<div id="state3" class="statecontent">State3 Specific Page Content Goes here</div><br />


This code will alove me to show content thats inside the different divs depending on what 'state' I choose in the drop down. But how do I connect the values of the drop down to a specific class instead of an id. The problem is of course that I want to show several divs that share a common class when i select a state in the drop down.

I would very much appreciate if anyone could point me in the right direction.

Paul

Answer

you can use class instead of Id like this

<div class="statecontent state1">State1 Specific Page Content Goes here</div><br />
<div class="statecontent state1">State1 Specific Page2 Content Goes here</div><br />
<div class="statecontent state2">State2 Specific Page Content Goes here</div><br />
<div class="statecontent state3">State3 Specific Page Content Goes here</div><br />

and your JQuery

$(document).ready(function() {
    $('#myselector').change(function() {
        $('.statecontent').hide();
        $('.' + $(this).val()).show();    
    });
});