Nadia Nadia - 7 months ago 6
Javascript Question

Insert numeration just for visible element

I have five

div
some of them with
display:block
and others with
display:none
, and it changes dynamically.
I'm trying to add title with numeration just for visible elements.
For example, If I have two visible elements, I should have "seance 1" for the first and "seance 2" for the second, but actually I have "seance 2" for both. This is my code:



$('#save').click(function() {
var countVisible = $('.panel-title:visible').length;
$('.panel-title').filter(':visible').each( function () {
for (i=0; i<countVisible; i++){
$(this).text('seance'+(i+1));
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="panel" style="display:none;" id="seance1">
<h4 class="panel-title"></h4>
</div>
<div class="panel" style="display:block;" id="seance2">
<h4 class="panel-title">text text</h4>
</div>
<div class="panel" style="display:none;" id="seance3">
<h4 class="panel-title"></h4>
</div>
<div class="panel" style="display:none;" id="seance4">
<h4 class="panel-title"></h4>
</div>
<div class="panel" style="display:block;" id="seance5">
<h4 class="panel-title">text text</h4>
</div>
<button id="save">save</button>




Answer

Do not add for loop. jquery each is enough

$('#save').click(function() {
    $('.panel-title').filter(':visible').each( function (i) {
      $(this).text('seance'+(i+1));
    });
  });

Fiddle -- https://jsfiddle.net/fkbqdepo/