Issue with Checkbox Input not Being Checked Upon Click (Styling with CSS Toggle Switch)

I have implemented a unique custom CSS toggle switch to customize the appearance of my checkbox inputs. Check out the project on GitHub.

However, I am facing an issue where clicking on the checkbox toggles registers the click twice and does not change the checked value. The checkbox remains unchecked if it started off that way, and stays checked if initially checked.

To demonstrate this problem, I have created a fiddle: https://jsfiddle.net/w1ug4jdc/

The HTML code for the styled checkbox is as follows:

<label class="switch-light switch-candy" onclick="doSomething($(this))">
  <input type="checkbox" />

  <strong>
    Wireless
  </strong>

  <span>
    <span>Off</span>
    <span>On</span>
    <a></a>
  </span>
</label>

You can find all the CSS styling in this file: https://github.com/ghinda/css-toggle-switch/blob/master/dist/toggle-switch.css

Answer №1

It is recommended to use the .prop() method instead of .attr() when checking the checked status, as checked is a property of the element. Avoid using inline event binding.

For more information, you can visit .prop() vs .attr()

Here is an example code snippet:

$('.switch-light.switch-candy').on('click', function() {
  $('#updates').append('<p>checked=' + $(this).find('input').prop('checked') + '</p>');
})
<link href="https://merkd.com/engine/ui/themes/lux/assets/css/toggle-switch.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label class="switch-light switch-candy">
  <input type="checkbox" />

  <strong>
    Wireless
  </strong>

  <span>
    <span>Off</span>
  <span>On</span>
  <a></a>
  </span>
</label>

<div id="updates"></div>

View Fiddle

To bind events to input elements and retrieve specific values:

$('.switch-light.switch-candy input').on('click', function() {
  $('#updates').append('<p>checked=' + this.checked + '</p>');
})
<link href="https://merkd.com/engine/ui/themes/lux/assets/css/toggle-switch.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label class="switch-light switch-candy">
  <input type="checkbox" />

  <strong>
    Wireless
  </strong>

  <span>
    <span>Off</span>
  <span>On</span>
  <a></a>
  </span>
</label>

<div id="updates"></div>

Updated Fiddle

Answer №2

Make sure to attach the onclick event to the input element instead of the label: https://jsfiddle.net/w1ug4jdc/1/

  <input type="checkbox" onclick="$('#updates').append('<p>checked='+$(this).find('input').attr('checked')+'</p>');" />

(Remember not to use inline events like shown above)

Answer №3

It appears that jQuery is not recognizing the "checked" attribute.

You can try using the :checked selector

$("label").click(function(){
  $('#updates')
    .append('<p>checked='+$(this).find(':checkbox').is(':checked')+'</p>');
})
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label onclick="">
  <input type="checkbox" />
</label>

<div id="updates"></div>

Answer №4

Encountered a similar issue while trying to set up this feature with asp net core MVC. The form submission wasn't functioning properly with just the checked property.

To solve this, I included the jQuery snippet below to ensure the checked attribute stayed in line with the checked property.

    $(document).on('click', '.switch-light.switch-candy input', function () {
    $(this).attr("checked", this.checked);
});

Initially, I selected the label for the event listener, but the control only responded on the second click (quite frustrating).

Really impressed with this library - definitely the best I've come across without any unnecessary complexity. Keep up the great work!

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

Why does variable passing use 'object Text' instead of passing values?

In my for loop, I am dynamically creating a table with radio buttons and trying to create labels dynamically as well. However, when I pass the variable to the label text node, it prints out 'object Text' on the page instead of the expected value. ...

Specify "Accept" headers using jQuery when fetching data within an iframe

I am working on a webpage where I am adding an iframe dynamically like this: $('<iframe id="testIframe" />').src('http://www.google.nl/').appendTo('body'); The accept headers being sent while loading the content in thi ...

Discovering elements through parent in Selenium

<div> <span>First line</span> <p>Second line</p> <span>Third line</span> <p>Fourth line</p> </div> My goal is to access the elements within the div tag using CSS or XPath selector ...

Error encountered while attempting to send a delete request to MongoDB due to connection refusal

Recently, I've been diving into a Next.js tutorial that involves working with MongoDB. Everything seems to be running smoothly when testing my API endpoints with Postman. POST, GET, and DELETE requests all go through without any hiccups. However, thi ...

How can you extract a specific object from a JSON string?

Currently, I am working on a script using JQuery within an ASP.NET page. Here is an example of a JSON string that I am dealing with: <input id="hfImages" type="hidden" value="[ {"ProductID": "000001", "Small": "http://myimages.com/images/I/75.jpg", " ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Access a local website path using JavaScript upon opening the browser

I need a Javascript function that can determine the day of the week when my html file is accessed, allowing me to automatically open a specific sub-page within my project. ...

Maintaining dual sets of files for website design projects

When working on website design and programming projects, I often wonder if it is common practice for experienced developers to maintain two sets of files - one for development and another for production like in jQuery. For instance, I have a project where ...

Using jQuery to interact with an API

jQuery offers powerful methods such as getJSON, get, and load which ultimately involve making AJAX calls. My goal is to access the API provided by www.eventsinindia.com for events happening in Mumbai during May 2009. This API returns data in JSON format. ...

Woocommerce - [product_categories] shortcode - Can I exclude specific categories from being displayed in the list?

Is there a way to hide specific categories (only two in this case) that are displayed using the [product_categories] shortcode? I have attempted to place these categories at the bottom of the list and used CSS to target them: .home .woocommerce ul.product ...

Sending data from JavaScript to PHP using the POST method

I recently learned that using ajax for data passing doesn't require a form or hidden value. I'm hoping to find an example to better understand how it works. index.js: function collectData(r) { // identifies the row index var i = r.pare ...

An ordered list placed within a div container in an HTML document

When I tried to format the ordered list with sub-items, I encountered an issue. There is a nested <ol> inside a <div>, but the numbering seems to be incorrect. Can you help me understand why? OL { counter-reset: item; padding-left: 10px; ...

Place API for Google Maps

I have been utilizing the Google Place API in my code, which has been working flawlessly. However, I encountered an issue when refreshing the page after a period of time, where Firebug displayed the error message: google.maps.event is undefined. Upon furt ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

The many potentials of looping through Sass maps

My sass map contains a variety of color shades, and the full code can be found on Codepen: $pbcolors: ( pbcyan : ( 50: #E5F5FC, 100: #CCEBF9, 200: #99D7F2, 300: #66C3EC, 400: #33AFE5, 500: #009DBF, 600: #008CAB, 700: #007C98, 800: #006D85, 900: #005D72 ...

Utilizing JavaScript to retrieve input names from arrays

This is the HTML form that I am currently working with: <form action="#" method="post"> <table> <tr> <td><label>Product:<label> <input type="text" /></td> <td><label>Price:<label> ...

Looking for a JavaScript UI for the optimal mapping experience with either Bing maps or Google maps

I am in the process of creating a basic prototype webpage utilizing Bing maps. My goal is to display multiple pins on a map that is embedded within my page. I plan to use a JavaScript UI to allow users to toggle checkboxes, which will then filter the resul ...

AngularJS filter date is returning a value of NaN-NaN-NaN

I'm facing an issue where the filter I developed is functioning properly on Chrome but not on Firefox. I am puzzled as to why this might be happening. myApp.filter('dateCustom', [ '$filter', function ($filter) { return funct ...

Tips for retrieving the $(this) element within an ajax success callback function

I am encountering an issue where I am unable to access $(this) inside the jQuery Ajax success function. Below is the code snippet in question: $.ajax({ type: 'post', url: '<?php echo site_url('user/accept_deny_friendship_reque ...

CSS - setting the background-image property is not displaying the image

.main_banner { background-image: url("../images/main_banner.png"); width: 100%; height: auto; } <!DOCTYPE html> <html> <heading> <title> ********** </title> <link rel="sty ...