How to deselect a checkbox using AngularJS

I have a checklist of items

<input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)"/>

and I need to unselect the currently selected checkbox

$scope.toggleSelection = function toggleSelection(id) {
window.alert("You cannot select this!");
//unselect the selected checkbox
}

Everything is functioning correctly, but I am unsure how to deselect the currently selected item.

Answer №1

Take the model and set it to false

<input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name, servicesModel)"/>

$scope.toggleSelection = function toggleSelection(id, model) {
    window.alert("You can't choose this option!");
    //deselect the chosen checkbox
    model = false; //update
}

Answer №2

Make sure to incorporate angular $event into the controller like this:

  $scope.handleToggle = function ($event, selection) {
      var checkbox = $event.target;
      var action = (checkbox.checked ? 'include' : 'exclude');
      $scope.updateSelection(action, selection);
  };

  $scope.updateSelection(action, selection) {
    if(action =='include') {
       selection = true;
     }  

    if(action == 'exclude') {
     selection = false;
     }
 }

In the html, update it as follows:

<input type="checkbox" ng-model="serviceModel" value="{{selection.name}}" id="{{selection.name}}" ng-click="handleToggle($event, selection.name)"/>

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

What is preventing ng-click from assigning a variable with the value from ng-repeat in AngularJS?

I'm currently working on a feature for an app that allows users to select font styles from Google Fonts for specific text elements. Here's the code snippet I have so far: <ul ng-init='headerFont="mono"'> <li ng-repeat=&apos ...

The value of Component.name is not consistent during the BUILD process in NextJS

I have multiple pages with different layouts. To switch between layouts, I am currently using the Component.name in _app.js. While this approach works during development, after building and starting the project with npm start, it seems like the Component.n ...

Implementing access restrictions for modules in NodeJS

In Node, is it possible to limit access or permit access only to specific modules from a particular module? Should I consider replacing the require function and object in the global scope for this purpose? I have concerns about the security of a certain mo ...

Expansive image coverage

My footer design includes a rounded left image, a repeating middle section, and a rounded right image. How can I ensure that it scales perfectly responsively without overlapping? Ideally, the solution would involve adjusting the width of the middle section ...

What is the best way to organize a table with multiple state variables using nested loops?

What is the best way to display multiple variables in a table using a loop, such as i,j,k? this.state = { materials: ['m1', 'm2'], quantity: ['2', '4'], unitPrice : ['12&apo ...

Long Polling results in the call stack size being exceeded to the maximum limit

I am working on a long polling function that needs to be triggered at a specific time, and then continue as long as the gallery has the updating class. The gallery is represented by $("... "). function pollGallery(gallery){ if (gallery.hasClass("upda ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

AngularJS flip card animation

Exploring the new AngularJS method for animations during page transitions, I am keen on integrating a card flip effect (resembling http://jsfiddle.net/nicooprat/GDdtS/) body { background: #ccc; } .flip { -webkit-perspective: 800; width: 400px; height: ...

Warning: An unhandled promise error occurred due to a validation error

I've been facing an issue for the past few days. Currently, I'm diving into learning the MEAN stack, but while trying to create a user on MongoDB using Mongoose schema, I encountered this problem: (node:93337) UnhandledPromiseRejectionWarning: ...

Manipulate HTML elements using JavaScript when a key is being held down

I'm currently developing a simple game using vueJS for the frontend. I have successfully created all the necessary objects and now my goal is to enable their movement when a key is pressed. However, I am facing an issue where the object only moves on ...

Guide on transferring data from an API using mapped React hooks

I am working with react hooks and attempting to pass a value to the delete function and execute the put function <Fab aria-label="delete" className={classes.fab} value={vacation.id} ...

Steps to reinitialize the error code after removal from the roster

Currently, I am working on creating a series of textboxes and dropdown menus using jQuery. So far, the add function is functioning smoothly without any glitches. However, my issue lies within the delete function. It works well when deleting sequentially, ...

Performing Vue CLI Global Upgrade

Struggling to create a new Vue.js project using the Vue CLI service, I encountered an error. With @vue/cli-service 3.0.0-beta.7 installed (confirmed by running vue -V), attempting to start a new project triggered the following error: ...

What could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

Encountering difficulty accessing the router during testing in Next.js

Hello, I'm currently attempting to test a scenario where when a button is pressed, it should redirect to '/'. Normally this works fine, but during testing it fails and shows the following error: Cannot read properties of null (reading ' ...

The callback information is not being properly identified

I need help with deleting an entire row when the Delete button is clicked using jQuery. Here is my current approach: UPDATE: I have made final adjustments to the click function: $(document).on('click', '.delete-assignment',function () ...

Javascript - Incrementing value upon key press, but limited to occurring only once

I am currently working on a script where I need to increment a variable by 5 each time the up key is pressed. The issue I am facing is that the variable keeps increasing continuously from a single keypress, whereas I want it to increase in steps of 5 (e.g. ...

HTML and JavaScript: Struggling to include multiple parameters in onclick event even after escaping quotes

I am struggling to correctly append an HTML div with multiple parameters in the onclick function. Despite using escaped quotes, the rendered HTML is not displaying as intended. Here is the original HTML code: $("#city-list").append("<div class='u ...

In JavaScript, use the following code to replace "(" with "(":

Is there a way to dynamically transform the string "Test(5)" into "Test\(5\)" using JQuery or Javascript? I attempted this approach, but it did not work as expected var str = "Test(5)"; str = str.replace("(","\("); str = str.replace(")"," ...

A useful method to generate dynamic and random interval values for each loop of setInterval in NodeJs

I am trying to implement a feature where a function in nodeJS triggers another function at random intervals within a specified range. Each time the loop occurs, I want the interval value to be different and randomly generated between 3 and 5 seconds. bot ...