Tips for changing the state of a toggle button with JavaScript

I need help creating a toggle button. To see the code I'm working on, click here.

In my JavaScript code, I am reading the value of a 'checkbox'. If the value is true, I add another div with a close button. When the close button is clicked, I remove this newly added div from the DOM.

Everything is functioning correctly so far.

However, I also want to toggle back the button. I have tried setting the value to false using the line:

document.getElementsByName("addUserConfirmation").checked = false;

After doing this, the value is set to false but the toggle button remains blue. How can I turn it off?

Here is the snippet of code in question:

function removeCardRevertToggleButton(button, container) {
    var parentContainer = document.getElementById(container);
    jQuery(parentContainer).children().remove();
    document.getElementsByName("addConfirmation").checked = false;
}

<div class="boxStyle">
    <span class="closeButton" requestid="" onclick="removeCardRevertToggleButton(this, &quot;inviteContainerContext&quot;)">×</span>
</div>

If you'd like to view the JSFiddle, you can find it here.

When the close ('x') button is clicked, I would like to switch the toggle button to the off position.

Answer №1

document.getElementsByName("addConfirmation")
retrieves an array of elements. To access a specific element in the array, you need to do this:
document.getElementsByName("addUserConfirmation")[0].checked

function removeCardRevertToggleButton(button) {
  document.getElementsByName("addUserConfirmation")[0].checked = false;
}
.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);
}


/* Rounded sliders */

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

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

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

  <div class="boxStyle">
    <span class="closeButton" onclick='removeCardRevertToggleButton(this)'>×
    </span>
  </div>

</body>

Answer №2

Here is the updated fiddle: https://jsfiddle.net/y709dzhx/

    HTML Code:
    <body>

     <label class="toggle-switch">
       <input type="checkbox" id="switch" name="toggleButton" checked>
       <span class="slider-round"></span>
     </label>

    <div class="content-box">
     <span class="remove-button"  onclick='hideElement(this)'>×
     </span>
    </div>

   </body>

JS Code:
    function hideElement(button) {
    alert("Clicked, new value = " + button.checked);
    //var parentDiv = document.getElementById(container);
    //jQuery(parentDiv).children().remove();

    document.getElementById("switch").checked = false;
    document.getElementById("switch").classList.add('slider:before');
}

I hope this meets your requirements!

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

What is the best way to emphasize case-insensitive searchtext matches in JavaScript?

If I have data containing words like Krishna, krishna, KRISHNA and I enter the search text as 'krish', it will retrieve all three words. However, when I want to highlight the matching result, only the exact matching part of the string is highligh ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

Module 'BrowserFetcher.js' could not be located

After updating all my npm packages, I encountered an issue when trying to run on my local server. The error message reads: Error: Cannot find module './BrowserFetcher.js' This error specifically points to a line in my puppeteer file located at - ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Guide to customizing color themes using Twitter Bootstrap 3

Recently, I dove into the world of Twitter Bootstrap 3 without any prior experience with earlier versions. It's been a learning curve, but I managed to set up a WordPress theme using it as the framework. All my elements are in place, but they all see ...

If an Angular reactive form component has a particular value

I am working with a group of radio buttons. When a user chooses the option "yes," I would like to display an additional input box on the form. Link to Code Example HTML.component <div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt- ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

What is the best way to incorporate multiple versions of jQuery on one webpage?

Is it possible to use multiple versions of jQuery on a single page? I need two different versions for various functions, but they seem to be conflicting with each other. If I implement jQuery noconflict, will the product scripts still work? <script typ ...

In Vue, reactivity does not extend to nested child objects

I am dealing with JSON data structured like this- items: { id: 1, children: [{ id: 2, parentId: 1, children: [{ id: 3, parentId: 2 }] }] } level-1 children represent parent items that all possess a parent_id of 1 (the roo ...

How can I incorporate multiple JSX files into plain HTML without using npm?

I have a question regarding importing JSX files in an HTML file without using npm and directly running it with LiveServer. I have two files, index.js and app.jsx, that I want to connect within my index.html script. How can I achieve this? Code: index.html ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...

Eliminate perfect-scrollbar functionality on mobile devices

I have applied the perfect-scrollbar class with 'height: auto' on mobile screens, expecting it to work properly. It's functioning well in responsive mode on the web. However, it does not scroll on mobile devices. @media (max-width: 992px) { ...

Displaying iFrame Border in React Native WebView

When attempting to dynamically add YouTube videos to my React Native app, I decided to utilize a combination of WebView and iFrame due to the incompatibility of the current react-native-youtube component with RN 16+. Although this solution works, the ifram ...

Tips for decreasing the width of a Grid column in MUI React

I have a total of 8 columns. The first column should be the smallest to accommodate a checkbox and does not require much space. I attempted to adjust the xl, lg, md values to 0.5 but was unsuccessful. Is there an alternative method to change the width of t ...

Guide on how to indicate the specific sheet on a Google Sheets API node.js batchUpdate request

I need to insert a blank row above all the data on the second sheet, but I'm having trouble specifying the exact sheet. Right now, the empty row is being added to the first sheet. const request = { spreadsheetId: 'spreadsheetId', ...

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

Tips on combining multiple HTML tags within a single div element

After extracting a value from an XML document using Javascript, I encountered a problem while attempting to generate multiple image tags based on that value. Despite my attempt with a for loop, only one image was being displayed. for(i=0; i<red; i++){ ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

Try utilizing an image to hold text content rather than a traditional div container

I am seeking help with displaying a brief image description at the bottom of an image. Currently, the display looks like this: https://www.bootply.com/render/Gwde8WHtot However, I would like the green background to align with the actual image rather than ...