Antoine Bergeron Antoine Bergeron - 24 days ago 10
CSS Question

Can't make jQuery dynamic selector work

I'm working on what seems to be a simple script, making buttons toggle divs in and out of view. I've done so before, but this time I'm using dynamic selectors in jQuery, and can't see what is wrong.

If I make the call a static one (ie: '#liste_21'), it works like a charm, but as the number of item is not now in advance, I would prefer to get the dynamic version working.

Any idea what's wrong?

Javascript

$(document).ready(function() {
$(".jour").click(function() {
var jour = $(this).text();
$('#liste_'+jour).slideToggle();
});
});


HTML

<div id="calendrierActivites">
<div id="nov20" class="jour">
<span>20</span>
</div>
<div id="nov21" class="jour">
<span>21</span>
</div>
<div id="nov22" class="jour">
<span>22</span>
</div>
</div>

<div id="liste_20">
<h2>20 novembre</h2>
</div>
<div id="liste_21">
<h2>21 novembre</h2>
</div>

<div id="liste_22">
<h2>22 novembre</h2>
</div>


https://jsfiddle.net/5yqsptry/#

Answer

JS Fiddle

var jour = $(this).find('span').text();

$(this).text() will get the text inside the div with class of jour and you're using the wrong selector.

Comments