jhjanicki jhjanicki - 11 months ago 55
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 = [];



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

if(count > 1){
for(var i =1; i<count;i++){


$msg.text('too many fields!');


function togglePanels(){
$.each(allCounts, function(index,value){



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}}

<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>


<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 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> <!-- 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 Source

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