DaniP DaniP - 5 months ago 6
jQuery Question

Jquery show multiple elements on Click

I have this situation:

Two columns with information one with questions and one with answers. I want to click in one question and show in the next column the answer. The question can have multiple answers so I need to show multiple elements with a single click.

I wrote some code taking a value with some

data attribute
like this:

HTML

<div class="evidence">
<div data-answer=".A,.B">1</div>
<div data-answer=".B,.C">2</div>
<div data-answer=".A,.C">3</div>
</div>
<div class="answer">
<div class="A">A</div>
<div class="B">B</div>
<div class="C">C</div>
</div>


Jquery

$(document).ready(function(){
$('.evidence').on('click','div',function(){
$('.answer div').hide();
var ans = $(this).data('answer');
$(ans).show();
})
})


Here is the Demo Fiddle.

It works but my question is if there is some way to improve my code avoiding write each classname in the answer column maybe showing the elements with
eq()
or some more efficient way.

Thanks

Answer

This is another way to store the answers. You store all the indexes (yeah I know, not really index since it starts with 1 but I couldn't find a better word) of the answers in an array and assign them to the index of the evidence.

var answers = {
    1: [1, 2, 3],
    2: [2, 3],
    3: [1, 3]
};

$('.evidence').on('click', 'div', function () {
    var ans = $(this).index() + 1;
    $('.answer div').hide().filter(function () {
        return answers[ans].indexOf($(this).index() + 1) > -1;
    }).show();
});
.evidence {
    width:200px;
    float:left;
}
.answer {
    width:200px;
    float:right;
}
.evidence div, .answer div {
    height:100px;
    line-height:100px;
    margin-bottom:15px;
    background:red;
    color:white;
    text-align:Center;
}
.answer div {
    background:orange;
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="evidence">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>
<div class="answer">
    <div>A</div>
    <div>B</div>
    <div>C</div>
</div>

And a fiddle to play with the code http://jsfiddle.net/g9hL881L/1/

Comments