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

How to align radio_button_tag and label_tag side by side in Rails using Twitter Bootstrap 2?

Struggling to align the radio_button_tag horizontally with its label_tag. (Utilizing HAML) =radio_button_tag(:animal, "dog") =label_tag(:animal, "Dog") Which classes should I use for these form helpers to have them positioned side by side as shown below: ...

Issue with document.referrer in Firefox: Unexpected behavior

I attempted to utilize the document.referrer function. It functions correctly in Google Chrome, however it does not yield the expected results in Mozilla Firefox. if (document.referrer.indexOf('stringToCheck') > 0) { //insert code here ...

Getting the draggable events area from the database in fullCalendar: A step-by-step guide

Currently, I am in the process of developing fullCalendar drag-and-drop events with a resource column. Initially, I hardcoded the draggable events area and now I am working on retrieving it from the database. Previously, the database had two tables - Resou ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Exploring the possibility of designing custom pageload tooltips inspired by jQuery validationEngine's visual style and interface

My website incorporates the jQuery.validationEngine plugin to ensure the accuracy of user input. The tooltips that accompany this validation feature are particularly appealing; they gracefully fade in and vanish when users interact with them. To visualize ...

Using the "number" input type gives the user the ability to easily remove numbers and leave the input field

I have integrated angularJS with rzSlider to provide users the option of manually entering a number value or using the slider to input the value. However, I'm facing an issue where if a user drags the slider and then deletes the entire input from the ...

Resources for ExpressJS

New to ExpressJS and trying to figure out how to reference images stored in the /public/images/ directory in my /public/stylesheets/styles.css The code snippet below doesn't seem to be working for me: .home-bg { background-image:url('../ima ...

Generate unique identifiers in HTML

Below is my HTML and JavaScript code: <!DOCTYPE html> <html> <head> <style> .custom-div { border: 1px solid green; padding: 10px; margin: 20px; } </style> <script> ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

CSS rule for targeting an element that does not have any child elements

I have a variety of different elements that are structured similarly to the following.. <div id="hi"> <div class="head"> </div> <div class="footer"> </div> </div> ..however, some of these elements do no ...

Embed the CSS from the iframe

** This question is purely hypothetical ** Imagine I have a website with the following code: <head> <style> body { background-color: red; } </style> </head <body> <p>blah</p> </body> If I were to embed th ...

Steps for choosing all choices in a multi-select menu without changing the order

What is the best way to choose all the options from a multiselect box using Java Script? ...

Utilizing React JS to Export Axios Response

I have an getAllUsers.js File that retrieves all users from the API. import axios from 'axios' export const fetchData = async () => { let response try { response = await axios.get('http://127.0.0.1:8000/api/users') } catc ...

Passing properties to the App component in React

Recently, I discovered how to pass props between components in React. Initially, I passed props from <FileTree> to <TextBox>, which you can see in action here: https://codesandbox.io/s/y018010qk9 After reorganizing my code, I structured my Rea ...

Automate website button clicks using Python and Selenium

I could really use some assistance: Currently, I have a Python/Selenium code snippet that carries out basic actions on a website to retrieve names, and it works perfectly fine. The objective: However, what I am aiming for is to automate these actions to ...

The printer is malfunctioning

My webpage has a div that includes various input fields with values assigned using jQuery. I wanted to print the contents of this div, so I found some code online to help me achieve this. However, when I try to print, the values in the input fields end up ...

Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular? var addProductModule = angular.module("addProductModule", []); addProductModule.factory("addProductService", ['$http', function ($http) { return { function savePro ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Unable to correctly declare and display UTF-8 character within JSON syntax

In my JSON object, there is an attribute that contains a unique special character - I've attempted to save the string in encoded UTF-8 as "\xF0\x9F\x94\x94" or tried displaying it using its HEX value - String.fromCharCode(0x1F514 ...

Place the information within a div container

If I already have something like <div class="key-element"></div> <div class="key-element"></div> <div class="key-element"></div> <div class="key-element"></div> <div class="key-element"></div> & ...