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

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

Retrieve the background color using code-behind

Despite its humorous appearance, I am having trouble with the Syntax :( I have a background color in my code behind file and need to correct the syntax here so that my Table displays the correct background color: <Table style="background-color:" &apos ...

Is there a way to use an Angular expression inside an HTML document to determine if a variable is a boolean type?

I'm working with an element in my HTML where I need to determine the type of a variable, specifically whether it's a boolean or not. <button process-indicator="{{typeof(button.processIndicator) === 'boolean' ? 'modalProcess&apo ...

Change the class name on a RichFaces 4 component to utilize themeroller functionality

Before I dive in, let me mention that I have thoroughly gone through the following content: Stackoverflow:how can i remove the css classes from a richfaces component However, my concern lies with version 4 as opposed to v3.x which was discussed in the re ...

Is it okay to incorporate this code into the existing plugin?

My plugin, known as "pluggable," has the ability to take any element with the class .plugin and inject the following markup into it: <span class="colorable">color me</span> Below is the original markup containing elements with the class "plug ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

Migrate the JavaScript variable created with 'passport' to an Express router

In my quest for authentication, I created the essential passportAuth.js file: module.exports = function(passport, FacebookStrategy, config, mongoose, fbgraph){ passport.serializeUser(function(user,done){ //to make user reference available across pages ...

Step-by-step guide on crafting your own twig with customizable color options using a colorpicker

I attempted to implement a color picker for my HTML form in Symfony, and it functioned flawlessly. However, when I tried using Twig for my form, I encountered difficulties meeting my expectations. I explored the GenemuFormBundle at https://github.com/gen ...

Enhabling Effortless Button Activation & Sustained Navigation State: Integrating Dynamic Navigation in React

"I am facing a React challenge and seeking assistance to implement a specific functionality with a button. At present, the button starts with a false state, but I intend for it to automatically activate and reveal a navigation component (nav) when the ...

How to adjust the "skipNatural" boolean in AngularJS Smart-Table without altering the smart-table.js script

Looking to customize the "skipNatural" boolean in the smart-table.js file, but concerned about it being overwritten when using Bower for updates. The current setting in the Smart-Table file is as follows: ng.module('smart-table') .constant(&ap ...

splitting xmlhttp.responsetext using loops

Currently, I have a JavaScript function that utilizes xmlhttp.responsetext to fetch data from MySQL. This data is then used to populate form fields in a dropdown menu, which has been functioning perfectly so far. However, the issue arises when I attempt to ...

Does JSX have an API that can handle self-closing tags, such as <br>, if they are not closed properly?

For my latest project, I've been working on a ReactJS component using JSX and it looks something like this: <script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( < ...

Ensure that the Javascript file is included before the CSS file to prevent any margin

I have external files for JavaScript and CSS. According to This question, they suggested that including JavaScript before CSS could enhance performance. However, I noticed a discrepancy in Chrome when I load JS before CSS - the .offset() function returns a ...

Sending a post request in PHP

Having an issue with a basic post form functionality where the data is not being transmitted correctly. After hitting submit, the process.php file is stating that no username and password have been entered. It seems like there may be a simple mistake that ...

Combine array in MongoDB containing nested documents

I need assistance with querying my MongoDB database: Specifically, I want to retrieve data that is nested within an array and filter it based on a specific key within the nested structure. The example document looks like this: [ { "name": ...

jquery slider ceases to function after refreshing the page in FireFox exclusively

For a while now, I've been using a slider without any issues. However, recently I noticed that in FireFox version 25 and up, the slider sometimes runs smoothly when the page loads and other times it doesn't. If it does work initially, refreshing ...

Updating the unordered list (UL) of rows in MySQL dynamically

Currently working on a test site that aims to function as a video playlist player pulling videos from the VIMEO API based on URL numbers (like vimeo.com/7100569) The setup involves storing a list of these URLs in a MySQL table. At this stage, I have manag ...

The getServerSideProps function in Next.js is only executed once, meaning it won't retrieve fresh data when accessed via next/router

I'm working on a Next.js application with Server-Side Rendering (SSR) where I have an async function called getServerSideProps that is exported like this: export const getServerSideProps = getGenericServerSideProps([""]); The getGenericServerSideProp ...