Ad

Css Toggle Switch Status

- 1 answer

So here is what I have for a toggle switch I'm using off of https://metroui.org.ua/inputs.html What Im trying to do is change the label thats before the switch/checkbox to say checked or not checked. If I click on the label it changes the switch but the text does not change. JavaScript:

$(document).ready(function() {
  $('#front_set').click(function() {
    if ($(this).is(':checked')) {
      $(this).siblings('label').html('checked');
    } else {
      $(this).siblings('label').html(' not checked');
    }
  });
});
<label for="front_set">checked</label>
<label class="switch-original right">
  <input type="checkbox" id="front_set">
  <span class="check"></span>
</label>

Ad

Answer

The issue: The label is not a sibling of the clicked checkbox, so you won't find it using siblings. The label is actually a sibling of the label that is the parent of the checkbox.

The solution: Use a different selector to find the label, so their relative positions don't matter much anymore. Using label[for="xyz"] you can find exactly that label that is bound to checkbox xyz, regardless of its position in the document. This makes your code more flexible too, because it won't break immediately if you reorganize your DOM.

var $myLabel = $('label[for="' + this.id + '"]');
$myLabel.html( $(this).is(':checked') ? 'checked' : ' not checked');

$(document).ready(function() {
  $('#front_set').click(function() {
    var $myLabel = $('label[for="' + this.id + '"]');
    $myLabel.html( $(this).is(':checked') ? 'checked' : ' not checked');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="front_set">checked</label>
<label class="switch-original right">
  <input type="checkbox" id="front_set">
  <span class="check"></span>
</label>

Ad
source: stackoverflow.com
Ad