Guide on how to turn off a checkbox "toggle switch" using JavaScript

Being relatively new to CSS and HTML, I recently experimented with creating a checkbox toggle switch using this resource. I now have a specific requirement to disable this toggle switch upon clicking a different button labeled 'Reset', making it appear as if it's in the OFF state with no background color. I believe a JavaScript solution is needed for this task, and I'm unsure if any CSS modifications are necessary. Any assistance on this matter would be greatly appreciated.

Answer №1

One way to deactivate any input element is by utilizing the

setAttribute("disabled", true)
method

For example, you can disable all input fields on a webpage like this:

const allInputs = Array.from(document.getElementsByTagName("input"));
allInputs.forEach((input)=>{input.setAttribute("disabled", true)})

If you have specifically named your input element with an id such as:

<label class="switch">
  <input type="checkbox" checked id="yourSwitch">
  <span class="slider round"></span>
</label>

You can toggle the disabled attribute using this line of code:

document.getElementById("yourSwitch").toggleAttribute("disabled");

Alternatively, you can disable it permanently with the following code:

document.getElementById("yourSwitch").setAttribute("disabled", true);

Answer №2

Here is the solution:

All you need to do is assign an id to the input and the rest will be taken care of automatically

document.getElementById("switch1").disabled = true;
document.getElementById("switch2").disabled = true;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

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

.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);
}

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

.slider.round:before {
  border-radius: 50%;
}
</style>
</head>
<body>

<h2>Toggle Switch</h2>

<label class="switch">
  <input type="checkbox">
  <span class="slider"></span>
</label>

<label class="switch">
  <input type="checkbox" checked id='switch1'>
  <span class="slider"></span>
</label><br><br>

<label class="switch">
  <input type="checkbox">
  <span class="slider round"></span>
</label>

<label class="switch">
  <input type="checkbox" checked id='switch2'>
  <span class="slider round"></span>
</label>

</body>
</html> 

Now, observe that the second toggle switch is currently disabled

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

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

What could be the reason for the meta viewport not functioning properly on Android devices with Cordova 5.1.1?

Ever since upgrading my app to cordova 5.1.1, I've noticed that the meta viewport no longer functions properly on Android devices. The app is not displaying correctly as a result. Despite trying various solutions, I am still facing this issue. Is ther ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

React JS is having trouble rendering an object that contains a list as one of its elements

I've been attempting to display the P_words list element with React using map: const f_data = { key: 2412, reviewed: 100, rating:4, P_words: [{ word: "Coolx", freq: 5 }, { word: "Dumbf&quo ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Style selector for dynamic drop-down menus

import React, { Component } from "react"; export default class FontChanger extends Component{ constructor(props){ super(props); this.state ={ selectedFont: "", currentFont: "", }; this.handleFon ...

A flex container containing two divs each with a white-space:nowrap element set at 50% width

How can I create a parent div that contains two child divs, each with a width of 50% that adjusts based on content? The issue arises when one of the child divs has an h3 element with white-space:nowrap;, causing it to exceed the 50% width. I attempted to ...

Encountering an Unexpected Token Error while using Jest in Next.js for node-modules

After setting up my Next.js project, I decided to install jest by running the command below: npm i --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom I then created a jest.config.json file with the following code snipp ...

Sorry, I'm unable to determine the value of 'title' because it is undefined

Here is the code for the "singleCard" component. When passing {{card.title}} and {{card.body}}, an error occurs: **Error in render: "TypeError: Cannot read property 'title' of undefined" found in ---> <SingleCard> at src/components/sing ...

I have noticed that when I use VBA's FindelementbyXpath function and manually copy & paste the xpath, my code works perfectly. But when I run the code again, I encounter a NoSuchElementError. Why does this

Looking to create an "Instagram Direct Message SENDING MECRO" URL = www.instagram.com/direct/inbox driver.FindElementByXPath("/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button/div/svg").Click After opening the link and copying/ ...

Saving a picture to local storage with the file input type in ReactJS

I am attempting to save an image in the browser storage once a user selects an image from their computer. <div className="add_grp_image_div margin_bottom"> <img src={img_upload} className="add_grp_image"/> <input type="file" class ...

What is the best method for retrieving the id from an <a> tag in HTML and passing it to a JSP

My dilemma involves a snippet of HTML code: <a href="mobile.jsp" id="s5" >Galaxy s5</a> <a href="mobile.jsp" id="iphone">Iphone 4S</a> <a href="mobile.jsp" id="xpr">Xperia</a> I am aiming to organize similar items on o ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Can I use jqPlot to create a separate division for the legend?

Is it feasible to move the legend to a distinct div using jqPlot? legend: { show: true, placement: 'outside', fontSize: '11px', location: 'n' } ...

What is the best approach for managing multiple HTTP requests in my specific situation?

I have a query about handling multiple HTTP requests in my code to ultimately get the desired result. Here is an outline of my approach: var customer[]; var url = '/api/project/getCustomer'; getProject(url) .then(function(data){ ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

Unexpected white space appears at the bottom of the page when rotating the device in iOS Safari

One issue I encountered on my website involves a meta tag: <meta name="viewport" content="width=device-width, initial-scale=1.0"> This, combined with height:100%; on the html and body tags, causes problems when viewed on Safari ...

What is the reason behind the sorting of sets in jQuery when using the .add() method?

Recently, I encountered an issue while adding multiple DOM objects (SVG elements) totaling around 3000 to an empty jQuery set using the .add() method. The process was taking an unexpectedly long time, causing the UI to freeze while the JavaScript code wa ...