Deselect the checkbox that has been selected using a JavaScript function

I have been searching everywhere for a solution and I am hoping someone in this community can assist me. I am working with a script that triggers when a checkbox is selected from a group of checkboxes. Each checkbox is given a value of "customer id".

<input type="checkbox" name="inv_add[]" onclick="setcid(\''.$result['cid'].'\')" value='.$result['id'].'/>

The purpose of the JavaScript function is to set a value in a hidden field, which will then inform the next page about the customer id of all checked boxes.

If a user selects a checkbox that belongs to a different customer (i.e., it does not belong to the group), I want to alert the user and then unselect the last box they checked. I'm able to display the alert message, but I am struggling with unchecking the box that was just selected by the user.

function setcid(cid) {

if (window.set_x === undefined) {
    sethidden = document.getElementById('cid');
    sethidden.value = cid;
    set_x = cid;
    alert ("Finished setting x");

}

else if (cid !== set_x){
    alert ("You are attempting to add two different companies to the same invoice");
    /* Uncheck the recently selected box by the user */
}

else {
    alert("They are the same");
    /* No modification needed */
}

}

Answer №1

If you want to include the this object when calling the function, simply pass it as a parameter:

http://example.com/oPq56/

XHTML

<input type="text" name="user_name[]" onclick="setID(\''.$result['id'].'\', this)" value='.$result['name'].'/>

JavaScript

function setID(id, element) {

...

    else if (id !== selected_id){
        alert ("You are attempting to select two different IDs");
                       element.checked = false;
        }

    else {
        alert("IDs match");
                       /*no changes needed*/
        }

}

Answer №2

To give your checkbox an ID, you can use chk_[TheIdOfTheHiddleField]:

<input type="checkbox"
       id='.$result['id'].'
       name="inv_add[]"
       onclick="setcid(\''.$result['cid'].'\')"
       value='.$result['id'].' />

You can uncheck it by doing the following:

document.getElementById("chk_" + cid).checked = false;

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

Altering information with the use of history.pushState throughout time

I've created a template that I want to load using the jQuery .load() function. However, during testing, I discovered that it's not loading at all. Here is the code I'm trying to use for loading: function open() { history.p ...

What is the reason for jQuery scripts not functioning properly when the scripts are placed above the jQuery library?

this script is functioning correctly: <div class="demo-gallery" data-pswp-uid="1"> <a class = "delete_button">click</a> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <script> ...

Using the .ajax() function with jQuery to retrieve data and then using .find() on that data

Currently I am facing an issue while trying to extract the body tag from the result of the .ajax() call. Instead of getting the desired result, I only see undefined logged into the console... This is the section of code causing the problem: $(document).r ...

Utilize Express.js to load a random HTML page

Hey there, it's Nimit! I could really use some assistance with my code. I'm trying to figure out if it's possible to load different HTML pages on the same URL like www.xyz.com/home/random. Can more than one HTML page be randomly loaded? I ...

Stripping away AM | PM from date variables

Is there a way to accurately calculate the difference between two datetime values in minutes without including AM|PM? When attempting to trim out the AM | PM from my code, I encounter errors (specifically NaN minutes). How can I safely remove this element ...

What methods does Express use to precisely measure time intervals shorter than 1ms?

Recently, I started delving into the world of Express, a web framework for Node.js. While experimenting with it, I noticed that whenever a webpage rendered by Express was refreshed, a series of log messages appeared on my Linux console, as shown below: GE ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Injecting dependencies in AngularJS when utilizing the controller-as syntax: A how-to guide

As I dive into the controller-as feature outlined in the documentation, I'm refining one of my controllers to align with their recommended syntax. However, I'm facing a challenge when it comes to injecting the $http service into my search() funct ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

how to create a smooth transition back to the original state after a click event

I've put in a lot of effort to make sure my code for the DECAY shapes is correct up to this point. The click event I implemented makes the shapes gradually start being affected, just as I intended. However, once I release the mouse or finger, it insta ...

Transforming the NavBar in React: A guide to dynamically updating values

I am facing an issue with my NavBar that changes based on certain events. The current setup works fine, but I don't want to render it in every class that loads a new page. Initially, I had the NavBar rendering inside App.js so it could appear on all p ...

Is there a way to implement the focus function and invoke a JavaScript function within an ASP.NET application?

Whenever I click on the textbox, a function is called. The code for that is: onclick="GetColorBack()" However, the GetColorBack function is only called when clicking on the textbox. If I navigate using the TAB key, it does not trigger the function. Is t ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

Firefox fails to render SVG animation

Currently, I'm attempting to incorporate this unique animation into my website: http://codepen.io/dbj/full/epXEyd I've implemented the following JavaScript code in order to achieve the desired effect: var tl = new TimelineLite; tl.staggerFromTo ...

The code functions correctly when retrieving information from a file, however, encounters issues when retrieving data

While working on my React application, I encountered a situation where I needed to read the value for translation from a file stored in the public folder. The files were saved at However, due to the dynamic nature of our data, we decided to store it in a ...

JavaScript: Creating a new entry in a key-value paired array

I am in the process of creating a dynamic menu for use with jQuery contextMenu. I have encountered an issue when trying to add a new element, as it keeps showing the error message 'undefined is not a function'. The menu functions correctly witho ...

Checking for null values using the "and/or" syntax

While reading an article on special events in jQuery, I came across a syntax that was unfamiliar to me: var threshold = data && data.threshold || 1 I have previously encountered the following: var threshold = data.threshold || 1 As far as I kno ...

Having trouble accessing the div element inserted by the Angular application

I've encountered an issue while trying to access a div that is injected into the DOM by an Angular app on the page. Below is the script I have placed at the end of the HTML page: $(document).ready(function () { var targetNode = document.querySelect ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...