龍王_
龍王_

Reputation: 73

Multiple instances of jQuery hide/show doesn't work

I have a simple bit of code that uses a dropdown to change the display property of some divs but I'd like to be able to have separate instances of it on the same page. It doesn't work right now because it uses class names to define the content to show and hide.

<div>
<select id="selectMe">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
<div class="group option1">asdf</div>
<div class="group option2">kljh</div>
<div class="group option3">zxcv</div>
<div class="group option4">qwerty</div>
</div>

<script>
$(document).ready(function () {
    $('.group').hide();
    $('.option1').show();
    $('#selectMe').change(function () {
        $('.group').hide();
        $('.'+$(this).val()).show();
    })
});
</script>

Is there a different way of targeting the .group divs so that I can repeat the whole block of HTML on the page and have it still work?

Hope you can help!

Upvotes: 2

Views: 269

Answers (1)

PSL
PSL

Reputation: 123739

You have created a wrapper anyways so make use of it. When you target use the parent/container as the context so that you can have it repeated anywhere else on the page. You can use closest to reach to the parent div and select the .group or .option within the parent of the dropdown.

$(document).ready(function () {
    $('.group').hide();
    $('.option1').show();

    $('#selectMe').change(function () {
       var container = $(this).closest('.container');
        $('.group', container ).hide(); //Select only the group under its parent
        $('.' + this.value, container).show(); //Select only the target div under its parent
    })
});

Fiddle

Upvotes: 2

Related Questions