Adnan Adnan - 3 months ago 25
jQuery Question

Replacing label text removes the enclosed span

I am trying to toggle the text and icons for the collapse panel in bootstrap. The icons seems to change properly but if i try to replace the label text, the spans are removed and i only see the icons. What is wrong with this?

HTML

<div class="row bgGray text-center">
<div id="divOptionsCI" class="col-xs-12 clickable" data-toggle="collapse" data-target="#containerFrequencyInflation">
<label id="lblMoreOptCI" class="clickable" style="height:30px;color:#FFF;">
<span class="glyphicon glyphicon-chevron-down glyphCollapseCI" style="top:3px;"></span>
More options
<span style="top:3px;" class="glyphicon glyphicon-chevron-down glyphCollapseCI"></span>
</label>
</div>
</div>


JS

$('#containerFrequencyInflation').on('shown.bs.collapse', function () {
$(".glyphCollapseCI").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
$("#lblMoreOptCI").text('Fewer Options');
});
$('#containerFrequencyInflation').on('hidden.bs.collapse', function () {
$(".glyphCollapseCI").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
$("#lblMoreOptCI").text('More Options');
});

Answer

Because the <span> is inside your <label>. You should change the text between the <span> elements, but not the <label> element.

Below I create a <span> for your text, and in the js, just change the text of that <span>:

<div class="row bgGray text-center">
    <div id="divOptionsCI" class="col-xs-12 clickable" data-toggle="collapse" data-target="#containerFrequencyInflation">    
        <label id="lblMoreOptCI" class="clickable" style="height:30px;color:#FFF;"> 
            <span class="glyphicon glyphicon-chevron-down glyphCollapseCI" style="top:3px;"></span> 
            <span id="lblMoreOptCISpan">More options</span>
            <span style="top:3px;" class="glyphicon glyphicon-chevron-down glyphCollapseCI"></span>
        </label>
    </div>
</div>

$('#containerFrequencyInflation').on('shown.bs.collapse', function () {                        
   $(".glyphCollapseCI").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
   $("#lblMoreOptCISpan").text('Fewer Options');
 });

$('#containerFrequencyInflation').on('hidden.bs.collapse', function () {        
  $(".glyphCollapseCI").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
  $("#lblMoreOptCISpan").text('More Options');
});