jhjanicki jhjanicki - 1 month ago 18
jQuery Question

jQuery toggleClass works for certain elements but not others (also using Mustache)

I am trying to create a HTML form where users can click on an add button to create another field, and each field can be toggled with only the most recently added field open and the rest closed. I got the add part to work, and I am using a class .hide (disply:none) to hide the panels. Below is my code:

$("document").ready(function() {
var template = $("#treatment-template").html(),
$target = $("#all-treatments"), // in html, where dynamic templates should be inserted
$btnAdd = $("#add-treatment"),
max = 10,
count = 1,
inputRow = [],
allCounts = [];



$btnAdd.click(function(e){
e.preventDefault();
addRows();
togglePanels();

});


function addRows(){
if(count <= max){
inputRow = {
count : count
}
var html = Mustache.to_html(template, inputRow);
$target.append(html);


if(count > 1){
for(var i =1; i<count;i++){
$("#invisible-part"+i).addClass("hide");
}
}

allCounts.push(count);

count++;
}else{
$msg.text('too many fields!');
}

}


function togglePanels(){
console.log(allCounts);
$.each(allCounts, function(index,value){
$("#show"+value).on('click',function(){
console.log(this);

$("#invisible-part"+value).toggleClass("hide");
});
});
}

addRows();


And here is my Mustache code:

<div class="treatment-wrapper">

<div class="row visible-part" id="visible-part{{count}}">
<p class="treatmentid inline-block"> TREATMENT {{count}}
</p>

<div id="show{{count}}" class="angledown inline-block">
<span class="fa-stack fa-2x">
<i class="fa fa-circle fa-stack-2x icon-background2"></i>
<i class="fa fa-angle-down fa-stack-1x"></i>
</span>
</div>

</div>

<div class="invisible-part" id="invisible-part{{count}}">
<div class="row">
<div class="col-lg-6">
<label for="start-treatment{{count}}">Start Date</label>
<input type="text" id="start-treatment{{count}}" name="start-treatment{{count}}" required value="yyyy-mm-dd">
</div>
<div class="col-lg-6">
<label for="end-treatment{{count}}">End Date</label>
<input type="text" id="end-treatment{{count}}" name="end-treatment{{count}}" required value="yyyy-mm-dd">
</div>

</div>
</div> <!-- end invisible part -->
</div><!-- end treatment-wrapper -->


However, for some reason the togglePanels() function isn't quite working. For example, when there are two fields / panels added then they both work, while if there are three fields / panels then only the last one is togglable, and if there are four fields / panels then one, two and four work, but not three. There doesn't seem to be a consistent pattern and I am quite confused about it. Any insight would be appreciated.

Answer

Remove the each loop and the function, do the following:

 $('body').on('click','#add-treatment',function(e){
          e.preventDefault();
          addRows();
 });
 $('body').on('click','.angledown',function(){
       $(this).closest('.visible-part').next().toggleClass("hide");
 });
Comments