AngularJS checkbox feature to tally the number of items that are currently selected or unselected

How can I use angularjs to count the number of selected and unselected checkbox items?

My HTML

    <label class="col-xs-5  pull-left" style="font-weight: bold; margin-left: 4px; margin-top: -17px;" >You have selected <font size="3" color="green">{{checkedResult}}</font> Customer(s)</label>

<tr ng-repeat="item in $data " >
             <td width="30" style="text-align: left" header="\'smsChkbx\'">
           <label>
            <input type="checkbox" class="ace" name="someList[]" value="{{item.somename}}" ng-model="checkboxes.items[item.somename]" />

Checkbox Function

 $scope.$watch('checkboxes.items', function(values) {
                        if (!$scope.mydata) {
                            return;
                        }
                        var checked = 0,
                            unchecked = 0,
                            total = $scope.mydata.length;
                        angular.forEach($scope.mydata, function(item) {
                            checked += ($scope.checkboxesSms.items[item.somename]) || 0;
                            unchecked += (!$scope.checkboxesSms.items[item.somename]) || 0;
                        });
                        if ((unchecked == 0) || (checked == 0)) {
                            $scope.checkboxes.checked = (checked == total);
                        }

                        **if(checked != 0 && unchecked != 0){
                            $scope.checkedResult++;
                        }**                    
                        $scope.tableParamsSms.reload();                                                
                         console.log($scope.checkedResult);
                        console.log((checked != 0 && unchecked != 0));
                        angular.element(document.getElementById("select_Sms")).prop("indeterminate", (checked != 0 && unchecked != 0));
                    }, true); 

It counts properly when I check for the first time, but also counts when I uncheck the selected ones.

I also want to count when multiple checkboxes are checked simultaneously.

Answer №1

It's important to create a function in AngularJS that will be triggered by clicking on a checkbox.

For example, use the following ng-click directive to call the function: ng-click="toggleSelection(item)"

Within this function, you can manage the selection process by adding or removing items from a list. Here's an example implementation:

$scope.toggleSelection = function(item) {
  var index = $scope.selectedItems.indexOf(item);
  if (index === -1) {
    $scope.selectedItems.push(item);
  } else {
    $scope.selectedItems.splice(index, 1);
  }
};

Finally, you can keep track of the number of selected items using the variable:

var count = $scope.selectedItems.length

Answer №2

I wasn't able to make changes to your code, but you could implement something along these lines:

HTML

<div ng-app>
  <h2>Example</h2>
  <div ng-controller="MyCtrl">
   <div ng-repeat="item in Items">
     {{item.name}} <input type="checkbox" ng-model="item.selected" ng-change="Checked(item)" />
   </div>
  </div>
</div>

AngularJS

function MyCtrl($scope) {
$scope.SelectedItems = [];
  $scope.Items = [
    {
        id: 1,
      name: "ABC",
      selected: false
    },
    {
        id: 2,
      name: "DEF",
      selected: false
    },
    {
        id: 3,
      name: "GHI",
      selected: false
    }
  ]
  $scope.Checked = function(item) {
    if (item.selected) {
        $scope.SelectedItems.push(item);
    }
    else {
        var index = $scope.SelectedItems.indexOf(item);
      if (index > -1) {
        $scope.SelectedItems.splice(index, 1);
      }
    }
    console.log($scope.SelectedItems)  //list of selected items
  }
}

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

Having trouble retrieving and displaying data from Mongo in Meteor with React

Seeking assistance with a React and Meteor issue. I am using TrackerReact to populate data in Mongo, but I am unable to display it in another component. When I console.log the data after the page loads, I see that the Mongo data loads after the page, causi ...

Using jQuery to access the value of the CSS property "margin-left"

I created a JavaScript game with moving divs that have different transition times. The game includes a function that is called every 1/100 seconds, which checks the position of the divs using: $("class1").css("margin-left") Here's the strange part: ...

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

Is there a way to modify the separator for ng-tags-input? By default, it is set as

Is there a way to preserve the space character when adding a space-separated tag in ng-tags-input instead of it being replaced with a dash? ...

Adjust the Vue.js required property to allow null values but not undefined

I need my component to accept both objects and null values, as Vue.js considers null as an object. However, I want the validation to fail if the value is undefined. Here's what I've attempted using vue-property-decorator: @Prop({ required: true ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

Is there a way to manually trigger a re-render of all React components on a page generated using array.map?

Within my parent component (Game), I am rendering child components (Card) from an array. Additionally, there is a Menu component that triggers a callback to Game in order to change its state. When switching levels (via a button click on the Menu), I want a ...

Leveraging JavaScript to generate a downloadable PDF document from the existing webpage

My goal is to have the user click a button labeled 'View PDF' or 'Download PDF' on the current webpage. This button would then execute JavaScript code to generate a PDF based on how the current page appears. I attempted using jspdf for ...

Scrolling with jQuery to create a fixed navigation bar

I'm having an issue with my navbar on my website. I used CSS and jQuery to keep it fixed at the top, but now when I click on a menu item, it doesn't scroll to that section of the page. Can anyone help me troubleshoot this problem? ...

Build a React application using ES6 syntax to make local API requests

I'm really struggling to solve this problem, it seems like it should be simple but I just can't figure it out. My ES6 app created with create-react-app is set up with all the templates and layouts, but when trying to fetch data from an API to in ...

Issues with the creation of an AngularJS table are causing functionality to malfunction

2021 UPDATE: Note: This question was drafted when I was still learning HTML and JS. If you are seeking assistance for an issue, this might not be very useful as my code was messy. Sorry for any inconvenience caused. The question will remain posted in acco ...

Vue: Load page content only after the route change is complete

Every time I visit a new route within the current session, I notice that the page loads and then takes about 2 seconds for the styles to be applied. This delay causes what is commonly known as CSS flashing or FOUC (Flash of Unstyled Content), which ultimat ...

Issue with showing Angular directive

I've been working on implementing an angular dropdown list with Bootstrap. The functionality includes a directive that allows the user to select a menu option from the dropdown and receive an alert message. To see the implementation in action, I have ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

Navigating in AngularJS with various URL parameters

Within my application, I am in need of using routes that require multiple attributes from the URL to be passed into PHP. The current setup that is functioning correctly is as follows: .when('/jobs/:type', { templateUrl: function(attrs){ ...

Is it possible for Netbeans 7.3 to debug a PHP script when triggered by a JSON request?

In my Netbeans 7.3.1 setup, I usually have no issues debugging PHP files with Xdebug when my site project is structured to generate the site directly from PHP code. However, I'm currently working on a site that consists mostly of HTML files and only h ...

JSON failing to show all values sent as a string

In a div element there is a table with 3 rows, a textarea, and a button. The JSON data populates the first 3 rows correctly but the textarea remains blank. My goal is to display the previous record from the database in the textarea. function ChangeLoadin ...

An element in defaultProps deemed as nonexistent

As I dive into routes and routing practice, I've encountered some challenges that have me stumped. The issue seems to be in the render method in App.js. The concept is simple - I'm working on a getDogFunc function that should help me locate a s ...

Having trouble integrating MaterialUI Datepicker, Dayjs, useFormik, and Yup

Currently, I am facing a recurring issue with the Material UI Date picker in conjunction with day js. The problem arises when I select a date on the calendar for the first time, it updates correctly in the text field but fails to work thereafter. Additiona ...

Typescript method fails to compile due to an indexing error

Imagine you're trying to implement this method in Typescript: setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) { let octdctruns: OctDctRun[] = [...this.octDctRuns]; const index = octdctruns.findIndex((o) => o.guid ...