Click on the checkbox to activate it using JavaScript

I'm trying to use JavaScript to toggle the checkbox status when clicking a button. The first button is supposed to uncheck the box and it's working correctly:

function clear() {
document.getElementById("check").checked = "";
}

However, I also have another button that should check the box if it's not checked and uncheck it if it is already checked. The code below doesn't seem to uncheck the box, even though switching the if statement works in the opposite way. Can anyone help me identify the issue?

function switchIt() {
if (document.getElementById("check").checked !== "checked") {
  document.getElementById("check").checked = "checked";
} else {
  document.getElementById("check").checked = "";
}

Any assistance would be greatly appreciated! Thank you!

Answer â„–1

toggle is a reserved word, please choose a different one

function toggleCheckbox() {
  var box = document.getElementById("check");
  
  if (box.checked) {
    box.checked = false;
  } else {
    box.checked = true;
  }
}

setInterval(toggleCheckbox, 1000);
<input type="checkbox" id="check" />

Answer â„–2

Consider "checked" as a boolean value, not as a string.

To toggle it, simply invert its current state like this:

var element = document.getElementById("check");
element.checked = !element.checked;

Here's a more detailed example:

var $toggle = document.getElementById('toggle');
var $checkbox = document.getElementById('checkbox');

var toggleCheckbox = function() {
   $checkbox.checked = !$checkbox.checked;
}

$toggle.addEventListener('click',toggleCheckbox);
<label>
  Checkbox:
  <input id="checkbox" type="checkbox" checked />
</label>
<button id="toggle">Toggle</button>

Answer â„–3

In order to achieve this, you will require a boolean.

Check out the following code snippet:

https://codepen.io/anon/pen/jJyXgO

let checkbox = document.querySelectorAll('#check')[0]

setInterval(function() {
  checkbox.checked = !checkbox.checked
}, 1000)

Answer â„–4

I've never witnessed the utilization of a string "checked" in this manner before. Consider using a boolean like so:

function toggle() {
    if (document.getElementById("toggleBtn").checked !== true) {
      document.getElementById("toggleBtn").checked = true;
    } else {
      document.getElementById("toggleBtn").checked = false;
    }
}

or you can simplify it with:

function toggle() {
    document.getElementById("toggleBtn").checked = !document.getElementById("toggleBtn").checked
}

Remember, switch is a reserved keyword, so make sure to pick a different name, just like I did with toggle()

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

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

JavaScript Slideshow Transition Techniques

I'm struggling to create a slideshow gallery using Javascript. However, I'm facing an issue where the code instantly jumps from ferrari.jpg to veyron.jpg, completely skipping over lamborghini.jpg. <!DOCTYPE html> <html> <head> ...

Importing XML data into a JavaScript variable using jQuery without displaying an alert message

Despite previously asking questions about loading XML into a JS variable, I haven't found a satisfactory solution. In my script, I declare a variable before making an ajax request and then assign the result to that variable. However, this only seems t ...

What techniques can I use to generate a 3D visual effect by shifting the background image layer as the user scrolls (creating a Parallax effect

I have combined two images in the heading; one on top of the other. My goal is to create a subtle vertical movement in the background image as the user scrolls, giving the illusion of depth. Both images share the same width, but the background image is tal ...

Is it possible for an AngularJS directive to compile a fresh element that has a second directive assigned to it?

UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this. I am exploring the creation of dynamic HTML usin ...

When using JSON stringify, double quotes are automatically added around any float type data

When passing a float data from my controller to a JavaScript function using JSON, I encountered an issue with quotes appearing around the figure in the output. Here is the JS function: function fetchbal(){ $.ajax({ url: "/count/ew", dataType: "jso ...

Transforming a single object into multiple arrays using AngularJS

Just starting out with AngularJS and I've got some data that looks like this { day1: 0, day2: 0, day3: 0, day4: 2 } Is there a way to convert this data into arrays structured like below? [     ["day1": 0],     ["day2": 0],   ...

Transferring data between actions following an AJAX request in Zend Framework

I am currently utilizing an ajax call to communicate with a controller in order to update the number of articles displayed on the webpage. I have established an action within the controller to handle this ajax request. Below is a snippet of the code: publ ...

"Utilizing jQuery to apply a class based on the attributes of CSS

Is there a way in jQuery (or plain JS) to create a condition based on whether a div has a specific CSS attribute? For instance, I need jQuery to apply position:fixed to an element's CSS when another element has display:none, but switch back to positi ...

Utilizing jQuery to seize events and handle AJAX callbacks

I am attempting to accomplish a simple task: capture any click event and send the URL to a PHP script. When using alert(a); the ajax.php is called every time. However, if I remove it, only once in every 20 clicks will work. I am wondering if this is due t ...

Warning: When VueJs OnMount props is utilized, it might display a message stating, "Expected Object, received Undefined."

This is my current component setup: <template> <Grid :items="items" /> </template> <script setup> import { ref, onMounted } from 'vue' import Grid from '@/components/Grid.vue' import { getData ...

Breaking down JavaScript arrays into smaller parts can be referred to

Our dataset consists of around 40,000 entries that failed to synchronize with an external system. The external system requires the data to be in the form of subarrays sorted by ID and created date ascending, taken from the main array itself. Each ID can ha ...

I recently implemented a delete function in my code that successfully removes a row, but now I am looking to also delete the corresponding data from localStorage in JavaScript

I have successfully implemented a delete function in JavaScript that deletes rows, but I also want to remove the data from local storage. This way, when a user reloads the page, the deleted row will not appear. The goal is to delete the data from local s ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

What is the best way to implement a CSS transition for styles that are dynamically created by React?

I have a situation where I am using a button component that is styled based on a theme provided by a context: The code in Button.js looks like: () => { const theme = useContext(themeContext); // { primaryColor: "blue" } return <button className ...

implementing a JavaScript function and declaring a variable from an HTML source

On my webpage, I have a feature that gathers a large amount of data using jQuery. My goal is to limit the number of results displayed by changing the shown results dynamically to create a false-page effect. This functionality is all handled through a singl ...

Applying the jqtransform plugin to all forms except for one

We've implemented the jQuery jqtransform plugin to enhance the appearance of our website's forms. However, there is one particular form that we'd like to exclude from this transformation. I made adjustments to the script that applies jqtrans ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

WordPress CSS & JS files failing to enqueue properly

My attempt to integrate my CSS and JS files with WordPress has not been successful. Although my CSS works through the Custom CSS tab, this is not an ideal solution. Below is the code from my functions.php file for your reference. Can you help me troublesho ...

Can you explain the distinction between locating an element by its class name versus locating it by its CSS selector?

Class name: var x = document.getElementsByClassName("intro"); CSS selector: var x = document.querySelectorAll("p.intro"); I'm a bit puzzled, are there any distinctions between the two methods or are they essentially the same? ...