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

Closing the modal by simply clicking outside of it's boundaries

Is there a way to close the modal by clicking outside of it using pure JS or AngularJS? I'm struggling to figure out how to implement this functionality. Any assistance would be greatly appreciated. View Fiddle .modalDialog { position: fixed; ...

Looking to streamline your webpack configuration in vue.config.js? Utilize webpack-chain for efficient setup. And, wondering how to leverage the speed-measure-webpack

Below is the setup in my vue-cli3 configuration file: vue.config.js: const path = require('path') const CompressionWebpackPlugin = require('compression-webpack-plugin') const SpeedMeasurePlugin = require("speed-measure-webpack-plugin" ...

yii2: Utilizing the power of dynamic calling in widgets

Imagine I have a widget called Widget1; In the view file, I call this widget like so: <?= Widget1::widget() ?> Clicking on an element should trigger a new instance of the widget and execute its JavaScript scripts. However, I am unable to get the s ...

Having trouble with the functionality of a simple jQuery toggle menu on mobile?

I am experiencing an issue with a simple toggle menu that utilizes jQuery's on: tap feature, but it is not functioning as expected: <nav id="mobile-nav"> <ul> <li>Item 1</li> <li>Item 2</li> ...

Creating an App on Shopify

After working on Shopify development for a little bit, I have encountered a specific requirement from my client that is not currently available in the app store. The task involves: Creating two discount tiers based on the total value of the cart (e.g. 1 ...

Ways to delete a property from an element that was originally included with jquery

On my jsp page, I am implementing a jQuery autocomplete feature for a text field with the id "mytextfield". jQuery(function(){ $("#mytextfield").autocomplete("popuppages/listall.jsp"); }); Sometimes, based on user input and pr ...

Protecting Angular Routes: Verifying HTTP-Only Cookie Authentication on the Server- CanActivate Function

I am utilizing an HTTP only cookie for authentication in my server: export const checkCookie = async (req: Request, res: Response) => { const token = req.cookies["token"]; if (!token) { return res.status(401).json({ message: "Unau ...

What is the best way to create an array in jQuery based on the presence of set variables?

Currently, I am working with 5 different variables in my project: var item_id var status var next_contact var email var phone_number var comment These variables are being sent to my server via a POST request enclosed in an array: data = {'item_id&a ...

Having trouble getting the .push() method in JavaScript to function correctly

I've encountered an issue while trying to develop a function that iterates through each item in an array and records the index of a specific item when found. In this particular function, whenever the item 'contraband' is detected during the ...

"Comparing the similarity and accessibility of using the same browser session with a Firefox or Chrome

I'm working on a solution to close and open the same session in my browser using a Firefox extension. The code I have currently closes the browser and then opens the last session, but it also opens another window which is not desired. I want to be abl ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Avoiding node_modules in Webpack 2 with babel-loader

After updating to Webpack 2, I've run into an issue with the "exclude" property in my "rules". It seems I can no longer pass "exclude" into "options". What is the correct approach to handling this now? Previously: { test: /\.js$/, loader: ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

When does JSON overload become a problem?

Creating a bookmarking site similar to delicious has been my latest project. To ensure an optimized user experience, I have decided to fetch all the bookmarks from the database table and organize them into a JSON object containing essential data such as id ...

Exploring the Method of Accessing data-* Attributes in Vue.js

I have a button that, when clicked, triggers a modal to open. The content displayed in the modal is determined by the data attributes passed to the button. Here is my button: <button class="btn btn-info" data-toggle="modal" data-t ...

Developing an npm module that is compatible with both web browsers and Node.js

Currently, I am in the process of developing an npm package that will cater to both web apps and other node modules. If my focus was solely on browsers, I would simply assign window.myExport = myExport; as a direct solution (unless there is a more contemp ...

Retrieve the parent node's class using JavaScript without relying on jQuery

Attempting to retrieve the class of the parent node of a selected element using JavaScript, but encountering issues with the following code snippet. Any guidance on what needs to be corrected? function getParentNodeClass() { var parentNodeClass = this.p ...

Issue: Trouble with ajax form functionality

I'm a beginner in ajax, js, and php. Recently, I set up a simple contact form. <form id="contact-form" method="post" action="process.php" role="form"> <div class="messages"></div> <div class="form-group"> <l ...

FullCalendar is encountering loading issues when trying to fetch data from JSON, with the

I am currently utilizing FullCalendar to create a schedule for theater rehearsals. After considering my options, I concluded that JSON would be the most efficient way to retrieve events from my MySQL database. In the JavaScript code for the calendar page, ...