Question

Using handlebars as the view engine for node.js, the following html is dynamically generated, repeatedly http://jsfiddle.net/4Q5PE/:

<div class="btnsContainer">
  <div class="btn-group" data-toggle="buttons">
    <label class="btn btn1"><input type="checkbox" class="theBtn1">btn1</label>
    <label class="btn btn2"><input type="checkbox" class="theBtn2">btn2</label>
    <label class="btn btn3"><input type="checkbox" class="theBtn3">btn3</label>
  </div>
</div>

<div class="Div1" style="display:none;">div1</div>

<div class="Div2" style="display:none;">div2</div>

<div class="Div3" style="display:none;">div3</div>

And I have this jQuery to toggle elements, but the matching repeated elements appear ALL together!

$(document).on("change",".theBtn1",function () {
    var $that = $(".Div1");
    $that.slideToggle();
    $(".btn2").removeClass("active");
    $(".btn3").removeClass("active");
    $(".Div1").not($that).slideUp();
    $(".Div2").not($that).slideUp();
    $(".Div3").not($that).slideUp();
});
...

I have tried various versions of jQuery traversing (.parent, .children, .siblings, .next, .previous), but what's a workable combination for getting only ONE element to appear?

Was it helpful?

Solution

You can make much more easier, if you can wrap the target div's in another container like

<div class="btnsContainer">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn1"><input type="checkbox" class="theBtn1"/>btn1</label>
        <label class="btn btn2"><input type="checkbox" class="theBtn2"/>btn2</label>
        <label class="btn btn3"><input type="checkbox" class="theBtn3"/>btn3</label>
    </div>
</div>

<div>
    <div class="Div1" style="display:none;">div1</div>
    <div class="Div2" style="display:none;">div2</div>
    <div class="Div3" style="display:none;">div3</div>
</div>

then

$(document).on("change", ".theBtn1", function () {
    var $nxt = $(this).closest('.btnsContainer').next();
    $nxt.children().not('.Div1').stop().slideUp().removeClass("active");;
    $nxt.children('.Div1').stop().slideToggle().toggleClass("active");;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top