Transform a checkbox input into two distinct buttons

I am trying to change the input checkbox that toggles between light and dark mode into two separate buttons. How can I achieve this functionality?

Check out the demo here: https://jsfiddle.net/ot1ecnxz/1

Here is the HTML code:

<input type="checkbox" role="switch" id="flexSwitchCheckChecked" checked onclick="myFunction()" />
<hr />
<button type="button" data-bs-theme-value="light"> Light </button>
<button type="button" data-bs-theme-value="dark"> Dark </button>
<hr />
<p>
This is a sample text
</p>

This is the JavaScript code:

function myFunction() {
    var element = document.body;
  element.dataset.bsTheme =
  element.dataset.bsTheme == "dark" ? "light" : "dark";
}

Answer №1

To replace a checkbox with 2 dedicated buttons, use the following code:

HTML :

<button type="button" data-bs-theme-value="light" onclick="setTheme('light')"> Light </button>
<button type="button" data-bs-theme-value="dark" onclick="setTheme('dark')"> Dark </button>
<hr />
<p>
    This is a sample text
</p>

Javascript:

function setTheme(theme) {
    document.body.dataset.bsTheme = theme;
}

Answer №2

Web Development

<button type="button" onclick="setTheme('light')">Light</button>
<button type="button" onclick="setTheme('dark')">Dark</button>

JavaScript Example

function setTheme(theme) {
   var element = document.body;
   element.dataset.bsTheme = theme;
}

Test out this code snippet

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

The custom directive containing ng-switch isn't being reevaluated when the value is updated

I have developed a unique directive that acts as a reusable form. The form includes an error message display section which utilizes ng-switch: <div ng-switch="status"> <span ng-switch-when="Error" class="text-error">An Error occurred</spa ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...

CSS Text ellipsis displays only the beginning of each paragraph

I want to add ellipsis to a text, but it keeps including the first line of all paragraphs. What I actually need is for only the first line of the content to have the ellipsis applied. Here is an example of the content: When using websocket to send message ...

The total sum of values within labels that share the same class

I am attempting to sum up all the values of class tmpcpa and store the result in final_cpa, but for some reason final_cpa always ends up being 0. document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmp ...

Retrieve an array from a JSON object by accessing the corresponding key/value pair using the utility library underscore

I have a dataset in JSON format (as shown below) and I am attempting to use the _.where method to extract specific values from within the dataset. JSON File "data": [{ "singles_ranking": [116], "matches_lost": ["90"], "singles_high_rank": [79 ...

Holding onto numerous AJAX requests while disconnected, then dispatching them once the network connection is

I'm working on an application that heavily relies on AJAX requests, requiring the rapid or concurrent sending of multiple calls. The code snippet provided serves as a basic wrapper for sending AJAX POST requests within the app. However, I've enco ...

Preventing Repetition in an HTML List using JavaScript

My HTML list is populated with values from JSON, and I have a button on the page. <button onclick="printJsonList()">CLICK</button> This button triggers the following JavaScript function: function printJsonList(){ console.log(ctNameKeep); ...

The usage of 'import.meta' is restricted to within modules and cannot be utilized outside of them

I am working on a project that involves Node + Express + Babel + ES6. Within this project, I have the following files: /package.json { "name": "test-backend", "version": "1.0.0", "description": " ...

Save a CSV file into a list, locate a specific key within the list, and retrieve the fourth value associated with that key

After thorough revision, the question now reads as follows: Take a look at this content in database.csv: barcode,ScQty, Name , Qty ,Code 123456 , 3 ,Rothmans Blue , 40 ,RB44 234567 , 2 ,Rothmans Red , 40 ,RB30 345678 , 2 ,Rothmans Gre ...

before sending the url with fetch(url), it is adjusted

My front end code is currently fetching a URL from a local node.js server using the following snippet: fetch('http://localhost:3000/search/house') .then(.... Upon checking what is being sent to the server (via the network tab in Firefox dev ...

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

Access to create permissions for collection "faunaDB" denied due to authorization privileges in FQL query using User Defined

I have a custom user role for security that has a predicate function for creating entries in a collection named formEntryData. When I try to create an entry without the function, it works fine. However, when I use the provided function below, I receive a p ...

Determining if a div is scrolled to the bottom in ASP.NET

Seeking help as I am unsure how to tackle this task. My project involves using asp.net, where I have a div that has overflow:auto enabled to display terms and agreements. Additionally, there is an asp.net checkbox control with visibility set to "false". ...

Error: The validation process failed due to missing information. The file name and path are both required for validation

In my current project, I am attempting to upload a file from the frontend to the backend and save it. However, I am encountering an error that looks like this: Error The error message is as follows: this.$__.validationError = new ValidationError(th ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

Ways to fix vulnerabilities found in an NPM audit

Upon conducting an NPM audit, I found 5 critical issues. To address 4 of them, I attempted to update @storybook/addon-essentials & @storybook/react, as they were marked as "patched in >=x.x.x", indicating that the latest versions should have resolve ...

To collapse a div in an HTML Angular environment, the button must be clicked twice

A series of divs in my code are currently grouped together with expand and collapse functionality. It works well, except for the fact that I have to click a button twice in order to open another div. Initially, the first click only collapses the first div. ...

Is it possible to utilize PDF.js once the PDF file has been downloaded?

My goal is to integrate PDF.js (or Viewer.js) with a Flask application, where I have already retrieved the file from a server. Instead of using PDFJS.getDocument('helloworld.pdf') I prefer to display the downloaded PDF in the browser through a ...

The module demoApp could not be instantiated because of an error stating that the module demoApp is not accessible

I am struggling to create a basic Single Page Application (SPA) using Angular and ngRoute/ngView. Unfortunately, I can't seem to get it to work properly. Every time I try, I encounter the error: angular.js:68 Uncaught Error: [$injector:modulerr] Fail ...