diego goncalves diego goncalves - 5 months ago 14
Javascript Question

how to change text label checkbox bootstrap?

How can I change the text corresponding to a checkbox when it is selected. I want to change the text to one value when selected and reverted back when the box us unselected.



<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
<div class="container">
<div class="row">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary ck">
<input type="checkbox"> off
</label>
<label class="btn btn-primary ck">
<input type="checkbox"> off
</label>
<label class="btn btn-primary ck">
<input type="checkbox"> off
</label>
</div>
</div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$('input[type=checkbox]:checked').on('change', function () {
$(this).text("on");
});
</script>




Answer

If you put the "off" in a span:

<label class="btn btn-primary ck">
  <input type="checkbox"> <span>off</span>
</label>

you can do this:

 $('input[type=checkbox]').on('change', function() {
    var status = $(this).parent().find('span');
    if (status.text() === "on") {
      status.text("off");
    } else {
      status.text("on");
    }
 });

Check out this fiddle: https://jsfiddle.net/wietsedevries/bahujj8u/1/

Comments