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

Error 400: The onCreate Trigger function for Cloud functions is experiencing issues with HTTP requests due to errors in the request

I am encountering an issue when attempting to add a trigger for Firestore OnCreate, as the deployment fails with HTTP Error: 400 stating that the request has errors. Essentially, my goal is to write to a new document if a record is created in a different ...

Sorry, but we couldn't complete your request: User verification unsuccessful: email must be provided

Every time I attempt to save a user's credentials to the mongo database, an error pops up saying: "User validation failed: email: Path email is required." I am clueless as to why this issue keeps happening. It only started occurring when I added the v ...

Utilizing query parameters as variables in rewrites with Next.js

My goal is to use Next JS to redirect requests from /home?id=123qwert to the new path of /home/123qwert. I'm struggling with extracting the query parameter from the source and using it in the destination. This is what I have attempted so far: as ...

What methods can you use to locate the CSS selector within HTML that meets certain criteria?

Is it possible to parse a given link and find CSS selectors with attributes that partially or completely match a specific keyword? For example, if the keyword is "print," I want to identify all CSS selectors in the link containing "print" in their name, id ...

What could be the reason behind the failure of this :after element?

I am facing an issue with the preloader on my webpage where the animation is not displaying as expected. The animation should appear on top of a dark black background before the page fully loads, but it seems to be missing. The CSS for the animation works ...

CodeIgniter Flexi Auth - Redirect users promptly upon login expiration

Is it possible to use the CodeIgniter Flexi Auth library to redirect a user to the login page immediately upon session expiration, displaying a message stating: "Your login has expired, please login again," rather than waiting until page load? I'm co ...

"Identify the protocol name (string) based on a specific port number in TCP/UDP communication

Is there a built-in function in any web-oriented language to return protocol names based on port numbers? For example, if we have the following code: protocol = get_protocol_name(22) print protocol We would expect it to print out "ssh". A more detailed ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

What are the best ways to enhance performance when making multiple require() calls?

I am in the process of developing a bot for my company's Mattermost server (similar to a Discord bot). Each command for the bot is housed in its own file, making it easier to manage and maintain. When a user wants to execute a command, they must send ...

How can I display lowercase am/pm instead of uppercase AM/PM with angularjs date filtering?

Hi there, I'm a newcomer to AngularJS and I have a specific requirement. The server is sending me two dates: start_date and end_date. In the scenario where both dates are in 'pm', such as Sun 29 Jan 5.00 pm to Sun 29 Jan 6.00 pm, I would li ...

Ways to establish a minimum height for material cards using Material UI

I am facing an issue with a card that contains a nested table. The card expands and shrinks based on the size of the table inside it. I want to prevent the card from shrinking when the table has no data or just one entry. Instead, I need the card to mainta ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

I am looking to narrow down the Google Places autocomplete suggestions specifically for India within Next Js

In my current project developed with Next.js, I am utilizing the react-places-autocomplete package to enhance user experience. One specific requirement I have is to filter out location suggestions for India only, excluding all other countries. Despite att ...

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

How can I make the input box TextField in Material UI with React expand to full width when selected?

I am currently customizing a Material UI form where the input box (Text Field) starts off at a width of 200px. My goal is to have the input box expand to 100% width only when it is selected or clicked on. ... <FormGroup sx={{ maxWidth: "200px" ...

"Failure in bundling with NodeJS using nexe and fusebox

I am attempting to convert a nodejs application into an .exe file. I initially tried using pkg, but encountered errors with half of the node-modules. Now, I am experimenting with a different method. However, when I run the following command: nexe index.js ...

What is the process for incorporating Web Assembly scripts into a React Native application?

I find myself wondering if this task is even feasible. If it is doable, I suspect we'll have to utilize WebViews, but maybe I'm just being overly analytical. Attempted to research this topic, but unfortunately, came up empty-handed. ...

Learn how to activate a JS native event listener using jQuery for the 'change' event

This question is unique from the one found at How to trigger jQuery change event in code. The focus here is on the interaction of jQuery with native event listeners, rather than jQuery event listeners. I am using addEventListener to bind a change event fo ...

Submitting forms with Ajax without reloading the page can cause errors in Internet Explorer

Simply put: Upon clicking the login button in Firefox, Chrome, or Safari, the form is submitted correctly, running a validation via ajax and opening a new page. However, in Internet Explorer (version less than 9), the submission attempts to post to the c ...

I am concerned about the security of my games as they can be easily hacked through right-click inspect. What measures can

As a newcomer to game development, I am creating web games using JS, HTML, and CSS. However, I have encountered an issue with preventing right-click inspect hacking, which has led to people hacking my games through this method. I am wondering, how can I s ...