Creating a function in AngularJS to select all checkboxes

I recently started working with Angular and I implemented a select all checkbox that checks all the boxes using ng-model/ng-checked.

    <th>
        <input type="checkbox" id="selectAll" ng-model="selectAll"/>
    </th>
    <th>
        ${Case Number}
    </th>
    <tr ng-repeat="item in c.onbCase>
        <td><input type="checkbox" name="checkbox" ng-click="checkboxFunc(item)"
                   ng-model="item.checked"
                   ng-checked="selectAll || item.checked"/>
        </td>
        <td>{{item.number}}</td>
    </tr> 

I have a function named checkboxFunc that sets item.selected to true when checked and adds the case number to an array:

$scope.onbNum = [];

    $scope.checkboxFunc =  function(item){
        if(item.selected == false) {
            if($scope.onbNum.indexOf(item.number)==-1){
                $scope.onbNum.push(
                    item.number
                )
            }
            item.selected = true;
        } else {
            if($scope.onbNum.indexOf(item.number)!==-1){
                var pos = $scope.onbNum.indexOf(item.number);
                $scope.onbNum.splice(pos,1)
            }
            item.selected = false;
        }
    }

Although the Select All checkbox is working fine to check all the boxes, I am looking for a way to ensure that all the case numbers are added to the array. How can I modify my function to achieve this?

Answer №2

If you want to track which checkboxes are checked, you can create an array like this:

$scope.checkedBoxes = [
  { id:1, isChecked:false },
  { id:2, isChecked:false },
  { id:3, isChecked:false }
];

Here are the functions you can use:

$scope.selectedIds = [];
$scope.checkAllBoxes =  function(){
    $scope.selectedIds = [];
    for(var i=0; i<$scope.checkedBoxes.length; i++){
        $scope.checkedBoxes[i].isChecked = $scope.selectAll;
    }
    if($scope.selectAll === true){
        for(var i=0; i<$scope.checkedBoxes.length; i++){
            $scope.selectedIds.push($scope.checkedBoxes[i].id);
        }
    }
}

$scope.checkboxClicked =  function(item){
    if(item.isChecked) {
        if($scope.selectedIds.indexOf(item.id) === -1){
            $scope.selectedIds.push(
                item.id
            )
        }
    } else {
        var pos = $scope.selectedIds.indexOf(item.id);
        if(pos > -1){
            $scope.selectedIds.splice(pos, 1);
        }
        $scope.selectAll = false;
    }
}

Here is an example of how you can use this in your HTML page:

<th>
    <input type="checkbox" id="selectAll" ng-model="selectAll"
       ng-click="checkAllBoxes()"/>
</th>
<th>    ${Case Number}
</th>     

<tr ng-repeat="item in checkedBoxes">
    <td><input type="checkbox" name="checkbox" 
      ng-click="checkboxClicked(item)" ng-model="item.isChecked" 
      ng-checked="selectAll || item.isChecked"/>
    </td>
    <td>{{item.id}}</td>
</tr>  

Hopefully this solution will work for you or at least give you some ideas.

Answer №3

I'm not entirely certain about the specifics of your question, but I hope my response can provide some assistance: Include ng-click in your selectAll input as shown below:

<input type="checkbox" id="selectAll" ng-model="selectAll" ng-change="checkAll()" />

Additionally, make sure to add the following function to your controller:

    $scope.checkAll = function () {
    if ($scope.selectAll == true) {
        angular.forEach($scope.c.onbCase, function(item) {
            if ($scope.onbNum.indexOf(item.number) == -1) {
                $scope.onbNum.push(
                    item.number
                );
            }
        });
    } else {
        angular.forEach($scope.c.onbCase, function (item) {
            if ($scope.onbNum.indexOf(item.number) !== -1) {
                var pos = $scope.onbNum.indexOf(item.number);
                $scope.onbNum.splice(pos, 1);
            }
        });
    }
}

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

Retrieving the date input from a React form powered by Bootstrap

Is there a way to extract a specific timestamp in the format yyyy-mm-dd from the code snippet below? handleDateChange = e => {} <Form.Group as = {Col}> <Form.Control type = "date" value = { this.state.closingDate } onChange = { ...

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...

Issue: Entering data in the input field for each row results in the same value being copied to the qty field

Currently, I have a field where users can enter the quantity for each row. Everything was functioning properly until I decided to add another input field for the pick option. Unfortunately, now it seems that whatever is entered in one field gets duplicated ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

Transferring Session ID between Express.js and Socket.io while dealing with iframes from distinct origins

My Node application built with Express.js and Socket.io is facing an issue where they are not sharing the same session ID when running under iframe with different origins. When accessed directly or through iframes with the same origin, everything works fin ...

JavaScript innerHTML not functioning properly when receiving a response from a servlet

Can someone help me troubleshoot the code below? I'm receiving a response from the servlet, but I can't seem to display it inside the div. Here is the response: lukas requests to be your friend &nbsp <button value="lukas"onclick="accfr(th ...

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Pattern to identify a JSON string with Regular Expressions

Currently, I am working on developing a JSON validator from the ground up and have hit a roadblock when it comes to the string component. My original plan was to create a regex pattern that aligns with the sequence specified on JSON.org: https://i.sstatic ...

Screen goes dark after switching to full-screen mode (panolens.js/three.js)

Utilizing a library known as panolens for displaying a 360-degree panoramic view, hinging on three.js. Within my application, there are two views: one containing custom content and the other serving as a container for panolens. Initially, the first view is ...

What is the best way to incorporate a version number into an Angular PWA application?

I recently created a PWA App using and packaged it into an msixbundle to submit to the Windows Store. However, I noticed that the builder automatically added a version number of 1.0.0.1 to the bundle. I would like to have manual control over the version ...

Using Three.js: Cloning Mesh and Material to Easily Toggle Clone Opacity

By using the command Mesh.clone();, it is possible to duplicate the mesh. Upon further investigation, I discovered that both the geometry and material are preserved in the clone. However, my goal is to independently adjust the opacity of each mesh. This le ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Tips on utilizing Jquery to extract an array containing UL, LI, and input elements

I am currently working with five ul lists, each of which may contain an input element. For example: <form id="testForm"> <ul id="1"> <li>TEST</li> <li>Gender: <select id="gender" name="gender"> ...

The selection feature is not supported for the type of input element in jQuery

I'm currently attempting to utilize AJAX to send a form with jQuery. However, upon clicking the submit button (which is technically a link), I encountered an error. The error displayed in the console is as follows: Failed to read the 'selection ...

jQuery restriction on selecting checkbox quantity

My web page contains multiple groups of checkboxes, with each group having checkboxes that share the same class. I am looking to not only restrict the number of checkboxes that can be checked in each group, but also implement a feature where if the maximum ...

"Troubleshooting the issue of nested jQuery Ajax requests failing to execute properly

UPDATE: I'm getting an error saying that my li tag is considered an illegal token. I'm unsure how to resolve this issue as I believed I was appending it within a ul tag I'm tasked with fetching a JSON array of public Github repositories and ...

Fetching dynamic JavaScript generated by PHP

I am creating a lightweight website and I have a piece of javascript code that I want to convert into a module by putting it in a separate file. This way, the code will only be loaded after a specific onClick event occurs. Successfully loading the javascr ...

Leverage the variable from one function in a different function within Three.js using Javascript

After loading an obj file using three.js, I attempted to obtain the 'X' position of its vertices and save it in a variable named 'pos' inside the objloader function within the init() function. My goal was to access this variable's ...

Circular movement in ThreeJS within a specified duration

I am currently working on creating a circular motion for an object within a set time frame. This project involves designing a clock with smooth motion. Instead of simply updating the position to fixed coordinates every time .getSeconds() changes, I aim t ...