CSS switch status toggle

Here's my code for a toggle switch from . I'm trying to change the label before the switch/checkbox to display "checked" or "not checked" based on the toggle state. When I click on the label, it changes the switch but not the text. 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>

Answer №1

One issue to address is that the label is not a direct sibling of the checkbox that was clicked on, making it difficult to target using the siblings selector. In reality, the label is actually a sibling of the parent label of the checkbox.

To solve this problem, consider using a different selector to locate the label, which will make their relative positions less important. By using label[for="xyz"], you can specifically target the label associated with checkbox xyz, regardless of its position in the HTML document. This approach also adds flexibility to your code as it will still work even if the DOM structure is rearranged.

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>
... (additional HTML markup)
      

Answer №2

Make sure to update the parent().siblings('label'), rather than .siblings('label') because the element you are binding the click event to is $(this), which is actually $('#front_set') (your input) and it is a child of <label>, not a sibling. Therefore, you need to move up a level using .parent():

$(document).ready(function() {
  $('#front_set').click(function() {
    if ($(this).is(':checked')) {
      $(this).parent().siblings('label').html('checked');
    } else {
      $(this).parent().siblings('label').html('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>

I'm curious about the purpose of

<span class="check"></span>
in your code. It seems unnecessary and can be removed without affecting the functionality.


Enhanced version:

A more reliable approach would be to bind events on change instead of click, as checkboxes might change their value without being clicked. Here is an improved version that should work seamlessly across different devices and browsers:

$(document).on('ready', function() {
  $.fn.extend({
    setLabel: function() {
      var label = $('[for="'+$(this).attr('id')+'"]').eq(0);
      $(label).text(($(this).is(':checked') ? '' : 'not ') + 'checked');
    }
  });
  $('#front_set').on('change', function(){
    $(this).setLabel();
  })
  $('#front_set').setLabel();
});
<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">
</label>

This implementation also defines the label check as a jQuery function, allowing you to call it on any element using .setLabel(). I have utilized GolezTrol's solution for selecting the label, providing more flexibility as it removes the parent/child dependency between the input and the label.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: failure of child element - the provided path is incorrect: "users/[object Object]", when implementing Firebase with Next.js

Having trouble with the identityNumber variable, which is giving an error message stating that a string is required. However, my identity number is already a string. Any assistance would be greatly appreciated. Additionally, the aim is to make the identity ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...

Issue encountered with SQL server 2008 due to connection error

My current struggle lies in the connection I am attempting to establish with SQL Server. Unfortunately, whenever I try pressing the period key or entering the server name, I encounter difficulty connecting to SQL Server. ...

Verify Radio Buttons in AngularJS

I thought validating a selection from a radio group would be simple, but I'm struggling to find the right solution. In my form, I need to ensure that at least one option is selected from the radio buttons. Using the 'required' attribute on e ...

In ReactJS, one can create a variable and include a map function by first declaring the variable and then using the map function within the component. If you

Having trouble integrating the accordian.js page into the app.js main page for compilation. Need help defining and writing out the function correctly, any suggestions? Below is my code: App.js: How do I incorporate the components from the accordian.js pa ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

Guide on sending a JavaScript variable as a URL parameter in Django

I need to pass a radio ID to my view, but I'm struggling with how to do it using the GET method in the URL: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/ma ...

Is it advisable to avoid using jQuery in Angular?

Is it true that using jquery in angular is considered bad practice? I've heard that when needing to manipulate the DOM, one should use directives. But why is it advised against to directly use jquery in the controller?? ...

Encountering a Syntax Error within the ng-click function of a button in AngularJS

I'm currently developing a mobile-based web application using angular js along with onsen ui. I've created a follow button on the user's profile page, allowing users to follow each other. However, when the user's profile loads and the a ...

Compiling with GatsbyJs throws an abrupt token error with 'if' being an unexpected token

I am working on a code snippet in GatsbyJS where I am extracting data from a StaticQuery using GraphQL and then rendering a component. The challenge I am facing is to conditionally check if a specific sub-object exists within the data object, and if it doe ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

Is it possible to insert IE conditionals within functions.php in WordPress?

One common practice is to include the following script in the <head> section specifically for Internet Explorer 9. <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> Wh ...

Adding a new row to a Bootstrap table while maintaining the consistent style

Is there a way to dynamically add a new table row with different styling using jQuery? I'm facing this particular issue and need help in solving it. Below, I have included some screenshots of my code and the view for better understanding. Here is the ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...

Switch the displayed image(s) based on the radio button selection made by the user

I need help implementing a feature on my website where users can change an image by selecting radio buttons. For example, there are three options: 1) Fox 2) Cat 3) Dog When the user chooses "Fox," I want an image of a fox to be displayed. If they then sw ...

Banner with video background (not taking up the entire page)

I'm currently working on a website project that involves using a YouTube video as the banner, but I'm facing some challenges in making it work correctly. So far, this is what I have: #video-background { position: absolute; right: 0; top:1 ...

Exploring jQuery AJAX Attributes during ajaxStart and ajaxStop event handlers

With my project consisting of over 40 ajax webservice calls, I am looking to incorporate additional debugging features. One such feature is a timing method which I have already developed using my Timer class/object in Javascript. I'm seeking assistan ...

jQuery Validator on a "Page-Level" Basis

I've already created a custom jQuery validator method that is linked to one or more specific dropdown lists in my asp.net project. jQuery.validator.addMethod("dropdownBoxHasItemSelected", function (value, select, arg) { var returnValue = false; ...

Using JS and d3.js to eliminate or combine duplicate connections in a d3.js node diagram

Hey there! Hello, I am new to working with js/d3.js and tackling a small project. Here are some of my previous inquiries: D3.js: Dynamically create source and target based on identical JSON values JS / d3.js: Steps for highlighting adjacent links My cu ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...