The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the correct jQuery function. On the other hand, when using the button, the property changes as expected. Can anyone explain why the span is unable to change the property?

$(document).on("click", ".taskcomplete2", function() {
  if ($(".taskcompletecheck").prop('checked')) {
    $(".taskcompletecheck").prop('checked', false);
  } else {
    $(".taskcompletecheck").prop('checked', true);
  }
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}
/* The slider */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}
.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}
input:checked+.slider {
  background-color: #2196F3;
}
input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}
input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}
.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label class="switch">
   <input type="checkbox" class="taskcompletecheck">
   <span class="slider round taskcomplete2"></span>
</label>
<button type="button" class="btn btn-danger taskcomplete2">Button</button>

Answer №1

To ensure the click event is attached to the span, you can do the following:

$(document).on("click",".taskcomplete2,.taskcompletecheck", function(){

    ....
});

$(document).on("click",".taskcomplete2,.taskcompletecheck", function(){
  if($(".taskcompletecheck").prop('checked')){
    $(".taskcompletecheck").prop('checked', false);
  }else{
    $(".taskcompletecheck").prop('checked', true);
  }
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<label class="switch">
   <input type="checkbox" class="taskcompletecheck">
   <span class="slider round taskcomplete2"></span>
</label>
<button type="button" class="btn btn-danger taskcomplete2">Button</button>

Answer №2

Using the for attribute on labels and the id on inputs can eliminate the need for JS in certain cases.

<label class="toggle-switch" for="complete-task">
   <input type="checkbox" class="task-toggle" id="complete-task">
   <span class="toggle-slider complete-task"></span>
</label>

By nesting the span element inside the label, clicking it will toggle the checkbox without the use of JavaScript.

Answer №3

To make the button click work, you can simply apply the for attribute, but remember to use e.preventDefault();

<label for="buttonToggle" class="switch">
   <input type="checkbox" class="taskcompletecheck">
   <span class="slider round taskcomplete2"></span>
</label>
<button type="button" id="buttonToggle" class="btn btn-danger taskcomplete2">Button</button>

Demo:

$(document).on("click",".taskcomplete2", function(e){

      if($(".taskcompletecheck").prop('checked')){
        $(".taskcompletecheck").prop('checked', false);
      }else{
        $(".taskcompletecheck").prop('checked', true);
      }
      e.preventDefault();
    });
.switch {
      position: relative;
      display: inline-block;
      width: 60px;
      height: 34px;
    }
    
    /* Hide default HTML checkbox */
    .switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }
    
    /* The slider */
    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ccc;
      -webkit-transition: .4s;
      transition: .4s;
    }
    
    .slider:before {
      position: absolute;
      content: "";
      height: 26px;
      width: 26px;
      left: 4px;
      bottom: 4px;
      background-color: white;
      -webkit-transition: .4s;
      transition: .4s;
    }
    
    input:checked + .slider {
      background-color: #2196F3;
    }
    
    input:focus + .slider {
      box-shadow: 0 0 1px #2196F3;
    }
    
    input:checked + .slider:before {
      -webkit-transform: translateX(26px);
      -ms-transform: translateX(26px);
      transform: translateX(26px);
    }
    
    /* Rounded sliders */
    .slider.round {
      border-radius: 34px;
    }
    
    .slider.round:before {
      border-radius: 50%;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="buttonToggle" class="switch">
   <input type="checkbox" class="taskcompletecheck">
   <span class="slider round taskcomplete2"></span>
</label>
<button type="button" id="buttonToggle" class="btn btn-danger taskcomplete2">Button</button>

Answer №4

$(document).on("click", ".switch", function(e) {

  if ($(".taskcompletecheck").prop('checked')) {
    $(".taskcompletecheck").prop('checked', false);
  } else {
    $(".taskcompletecheck").prop('checked', true);
  }
  console.log("Status :: "+$(".taskcompletecheck").prop('checked'));
  e.preventDefault();
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}


/* Hide default HTML checkbox */

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}


/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #2196F3;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label class="switch">
   <input type="checkbox" class="taskcompletecheck">
   <span class="slider round taskcomplete2"></span>
</label>
<button type="button" class="btn btn-danger taskcomplete2">Button</button>

Event is being triggered on the parent element.

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

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

Looking for a jQuery plugin that helps with form alignment?

In a blog post comment, I came across an interesting jQuery form alignment plugin: jQuery.fn.autoWidth = function(options) { var settings = { limitWidth : false } if(options) { jQuery.extend(settings, options); }; ...

What's the reason this picture isn't displaying in its full size?

I am having trouble adjusting the size of this image to fit the full width, but there seems to be some remaining space on the right side. Category: CSS/HTML /* Header */ .header { background: url('https://picsum.photos/1920/1080') center ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

Internet Explorer is unable to recognize the .less file format

I have created a less file that works perfectly in Chrome and Firefox, but it is not being recognized in IE 9. Does anyone have suggestions on how to make it run in IE 9.0? Below is a sample of the CSS code: @import "../core/variables.less"; @import "Mi ...

Only show a single li element in CSS at a time

I'm working with Angular 2 and I have a list: <ul> <li *ngFor="let show of (ann)"> {{show}} </li> </ul> I want to show one item from the list every 3 seconds in an infinite loop. Here&apos ...

The bug in Polymer 1.0 where a custom element is causing issues when clicking under the toolbar

Issues have arisen with a custom element I created, named <little-game></little-game>. Here is the template code for <little-game></little-game>: <template> <a href="{{link}}"> <paper-material elevation=& ...

Attempting to encourage a user to follow another user and display a notification

As I work on building a website in CodeIgniter, I have a requirement to implement a feature that allows users to follow other user accounts. I am looking for guidance on how to refresh the code using AJAX at regular intervals. Any helpful suggestions on ...

Error occurred during the file watch process in PhpStorm after saving the CSSO file

Following the advice in the official PhpStorm documentation, I have implemented a CSS minifier. However, upon attempting to use it, I encountered the following error: cmd.exe /D /C call C:\Users\douglas\AppData\Roaming\npm\css ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Styling a nested scrollbar using JQuery

I am looking to customize two scrollbars using a jquery plugin or JS library. Here is the HTML code: <div id="container"> <div class="fixedHeightContainer"> <div class="fixedHeightContent"> Lorem ipsum dolor sit amet, con ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Convert price to Indonesian Rupiah currency format with the help of Vue.js

Can someone help me convert the price format from IDR 50,000.00 to IDR 50.000 using JavaScript and Vue? I found a script on this website, but I am having trouble understanding how it works. The script looks like this: replace(/(\d)(?=(\d{3})+(?: ...

A dynamic image carousel featuring multiple images can be enhanced with fluid movement upon a flick of

I am trying to enhance this image slider in HTML and CSS to achieve the following objectives: 1. Eliminate the scroll bar 2. Implement swipe functionality with mouse flick (should work on mobile devices as well) 3. Make the images clickable .slider{ ove ...

Utilizing typesafe trpc in Node.js to efficiently transfer data between routes

I have successfully implemented an end-to-end typesafe API using the T3 Stack and can access all the data and types in my Next.js app. However, I also have a Node.js backend to populate my database with. My Node.js setup is as follows: app.use( '/t ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

Verify if the username is present in the database using AJAX

I'm looking to enhance my registration form by checking if a username already exists in the database. I have some questions regarding AJAX: How can I create an AJAX request on_change function for username validation? $('#username').change(f ...

Can SailsJS be used exclusively for API processes?

Can SailsJS be used solely as an API? After downloading the Sails project, is it possible to exclude the views and focus only on utilizing Sails as an API? ...

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

Adjusting webpage background with JavaScript

I've been struggling with this for the past six hours and can't seem to get it right. I've checked out various solutions on Stack Overflow, but nothing seems to work. What am I missing here?!? My html5 page doesn't have a background an ...