Discover the method for retrieving the value of a toggle-style checkbox

I am currently working with a toggle switch checkbox and I need to extract its value using JavaScript or jQuery when the state changes.

Based on this value, I aim to highlight the text of the label associated with the toggle switch, whether it's option1 or option2.

Any assistance in resolving this issue would be greatly appreciated.

.checkbox.checbox-switch {
  padding-left: 0;
}

.checkbox.checbox-switch label,
.checkbox-inline.checbox-switch {
  display: inline-block;
  position: relative;
  padding-left: 0;
}
... (CSS styles continue)
<div class="checkbox checbox-switch switch-primary">
  <label id="option1" for="switch1">Option1</label>&nbsp;
  <label>
    <input type="checkbox" name="" checked="" id="switch1" />
    <span></span>
  </label>
  <label id="option2" for="switch1">Option2</label>
</div>

Answer №1

Let me know if this meets your requirements :)

$('.checbox-switch label#option1, .checbox-switch label#option2').click(function() {
  var getID = $(this).attr('id');
  $('.checbox-switch label').removeClass('selected');
  $(this).addClass('selected');
  console.log(getID);
})
.checkbox.checbox-switch {
    padding-left: 0;
}

.checkbox.checbox-switch label,
.checkbox-inline.checbox-switch {
    display: inline-block;
    position: relative;
    padding-left: 0;
}
.checkbox.checbox-switch label input,
.checkbox-inline.checbox-switch input {
    display: none;
}
.checkbox.checbox-switch label span,
.checkbox-inline.checbox-switch span {
    width: 35px;
    border-radius: 20px;
    height: 18px;
    border: 1px solid #dbdbdb;
    background-color: gray;
    border-color: gray;
    box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset;
    transition: border 0.4s ease 0s, box-shadow 0.4s ease 0s;
    display: inline-block;
    vertical-align: middle;
    margin-right: 5px;
}
.checkbox.checbox-switch label span:before,
.checkbox-inline.checbox-switch span:before {
    display: inline-block;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background: rgb(255,255,255);
    content: " ";
    top: 0;
    position: relative;
    left: 0px;
    transition: all 0.3s ease;
    box-shadow: 0 1px 4px rgba(0,0,0,0.4);
    top:-2px;
}
.checkbox.checbox-switch label > input:checked + span:before,
.checkbox-inline.checbox-switch > input:checked + span:before {
    left: 16px;top:-2px;
}

/* Switch Primary */
.checkbox.checbox-switch.switch-primary label > input:checked + span,
.checkbox-inline.checbox-switch.switch-primary > input:checked + span {
    background-color: rgb(103, 209, 224);
    border-color: rgb(103, 209, 224);
    /*box-shadow: rgb(0, 105, 217) 0px 0px 0px 8px inset;*/
    transition: border 0.4s ease 0s, box-shadow 0.4s ease 0s, background-color 1.2s ease 0s;
}
.checkbox.checbox-switch.switch-primary label > input:checked:disabled + span,
.checkbox-inline.checbox-switch.switch-primary > input:checked:disabled + span {
    background-color: gray;
    border-color: gray;
   /* box-shadow: rgb(109, 163, 221) 0px 0px 0px 8px inset;*/
    transition: border 0.4s ease 0s, box-shadow 0.4s ease 0s, background-color 1.2s ease 0s;
}
.selected { border-bottom:1px solid cyan; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox checbox-switch switch-primary">
     <label id="option1"for="switch1">Option1</label>&nbsp;
      <label>
          <input type="checkbox" name="" checked="" id="switch1"/>
          <span></span>
      </label>
     <label id="option2" for="switch1">Option2</label>     
</div>

Answer №2

To handle the specified event, you must incorporate an event listener:

Learn more about addEventListener

The addEventListener() function in EventTarget enables the setup of a function to be executed when a particular event is triggered on the target. Common targets include Element, Document, and Window, although any event-supporting object can serve as the target.

When using addEventListener(), you are essentially adding a function or an object that follows the EventListener interface to the list of event listeners for the specified event type on the respective EventTarget.

Here's an example:

let test = document.querySelector('#switch1');

test.addEventListener('change', function() { 
  if (this.checked == true) {
    console.log('true');// perform actions here
  } else {
    console.log('false')// perform actions here
  }
 
})
.checkbox.checbox-switch {
  padding-left: 0;
}

.checkbox.checbox-switch label,
.checkbox-inline.checbox-switch {
  display: inline-block;
  position: relative;
  padding-left: 0;
}

/* Additional CSS code here */

<div class="your custom layout">
  <label id="option1" for="switch1">Option1</label>&nbsp;
  
  <input type="checkbox" name="" checked="" id="switch1"/>
    
  <label id="option2" for="switch1">Option2</label>
</div>

For future reference, below is an enhanced example showing how to toggle a class on change:

let test = document.querySelector('#switch1');

test.addEventListener('change', function() {
  if (this.checked == true) {
    console.log('true'); // perform desired action 
    switchTest()
  } else {
    console.log('false') // perform desired action
    switchTest()
  }

})

function switchTest() {
  let options = document.querySelectorAll('label[id^=option]');
  for (i = 0; i < options.length; i++) {
    options[i].classList.toggle('highlight');
  }
}
.checkbox.checbox-switch {
  padding-left: 0;
}

.checkbox.checbox-switch label,
.checkbox-inline.checbox-switch {
  display: inline-block;
  position: relative;
  padding-left: 0;
}

/* Additional CSS code here */

.highlight {
  background: yellow;
}
<div class="custom layout">
  <label id="option1" class="highlight" for="switch1">Option1</label>&nbsp;
  <input type="checkbox" name="" checked="" id="switch1"/>
  <label id="option2" for="switch1">Option2</label>
</div>

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

Tips for executing specific javascript on small screens or mobile devices

I am currently in the process of developing a Vue web application that needs to be functional on all devices. I have certain code that should only run on small screens or mobile devices. Right now, I am using an if statement with $(window).width() to achie ...

Is it possible to achieve partial text stylization in Vue using Nuxt.js?

We're currently developing a Vue application Is there a way to style text partially, similar to this example? Although creating exact constraints from ellipses may not be possible, the functionality could still be achieved procedurally. ...

Ways to eliminate content inside an anchor tag

Currently, I am in the process of developing a WordPress blog that utilizes the Woo Themes Definition theme. I have encountered an issue where text reading "previous" or "next" appears on the arrows only when using Safari on a Mac machine. You can find mo ...

Using Ruby method with two render statements and handling JQuery AJAX call response

I currently have a set of methods in a controller that requires validation for each one. To streamline this process, I created a validation method within the application controller. My goal is to invoke this validation method at the beginning of each indi ...

How to send data to Material-UI drawer components

In the component called Setup, there are input fields that each hold their own data stored in an object named dropdowns. Alongside each input field, there is a drawer component containing the ID of that specific input field. I have a function called handle ...

"Securing Your Web Application with Customized HTTP Headers

I'm currently working on setting up a POST request to a REST API (Cloudsight) with basic authorization. Here is the code I have so far: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.cloudsightapi.com/image_requests", true); xhr.setRequ ...

Enable users to choose multiple rows at once or alternatively choose by checking the checkboxes

When using Tabulator with the setting table.selectable = true, any cell click selects the row. However, I specifically want rows to be selected only via checkboxes, so I set selectable = false. The issue now is that the checkboxes behave like a radio butt ...

Revamping the vertices and UVs of DecalGeometry

I am currently experimenting with ThreeJS decals. I have successfully added a stunning decal to my sphere. Below is the code snippet I am using to place the decal on my sphere. (Please disregard any custom classes mentioned in the code.) // Creating the ...

What is the process for incorporating a script function into a React application?

Recently, I've been attempting to integrate the external application Chameleon into my React application. To achieve this, I need to incorporate the javascript function within my application. I prefer it to be invoked only in specific scenarios, so I ...

Hover over parts of an image to bring attention to them

I am interested in developing a webpage featuring a black and white image of 5 individuals. When hovering over each person, I would like them to illuminate and display relevant information in a dialog box next to them. Do you have any tips on how I can ac ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Storing Byte Array in a File using JavaScript

I am working on a Java REST webservice that returns documents as byte array. I am trying to write JavaScript code that will retrieve the response from the webservice and save it to a file for downloading as a PDF. However, when testing my sample code, the ...

Creating a custom PHP webpage and integrating it with a WordPress theme

I'm looking to develop a unique php and javascript page that is integrated with my existing Wordpress theme. Can anyone provide guidance on how to achieve this? Appreciate the help! ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

Arrangement of tables using HTML and CSS on the outdoor patio

Looking for advice on how to align buttons in the last column of a table outside of the table but in the same row. The attached image shows the current layout: https://i.sstatic.net/Ex5AR.png ...

Challenges encountered with Material-UI elements

Attempting to implement the http://www.material-ui.com/#/components/drawer (Docked Example) component from Material-UI in conjunction with ReactJS. An error is encountered with the "=" sign in this line: handleToggle = () => this.setState({open: !this ...

Exploring the method to extract a value from an array of objects using JSON parsing in Appcelerator

Visualize an artificial json response, here's the string representation of this JSON... [{"A":"1","B":{"name":"joe","lastname":"jones"},"COLORS:{"red":"rojo","blue":"azul"},"active":"yes"}] I am aiming to extract the name "joe" using the following c ...

How can I determine if a page is being rendered in Standards mode or Quirks mode by IE7?

Having some issues with CSS on a webpage. The code is valid and adheres to Strict HTML standards. It displays correctly in most browsers, but I'm experiencing problems in IE (specifically version 7). Is there a way to determine if the page is being re ...

How can I configure the Google Chrome script debugger to pause on exceptions?

Is there a way to automatically interrupt the program when an exception is encountered? ...

Creating Highcharts series with dynamic addition of minimum and maximum values

I am currently working with a Highcharts chart that includes multiple tabs allowing users to display different data on the graph. I am dynamically adding series for each of these data points, which has been functioning well. However, I have encountered an ...