Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the values of multiple checkboxes in AngularJS?

In my app I got 7 checkboxes. I want to get the value of the selected checkbox and store into an object. Ff it is deselected I want to remove it in the object.

HTML

<span ng-repeat="days in selectDays">
    <input type="checkbox" id="{{days}}" ng-model="daysSelected"/>
    <label for="{{days}}">{{days}}</label>
</span>

Controller

$scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$scope.selectedList = {}; //this is the object to store the selected checkbox values
like image 694
Kishan Avatar asked Dec 08 '16 11:12

Kishan


People also ask

How to get multiple checkbox checked value in Angular?

The MultiSelect has built-in support to select multiple values through checkbox, when mode property set as CheckBox . To use checkbox, inject the CheckBoxSelection module in the MultiSelect.

What is Ng true value?

ngTrueValue. (optional) expression. The value to which the expression should be set when selected.


1 Answers

The following code is a simple approach -> check this plunker. This example delivers you a very simple KISS principle handling for mulitple autogenerated checkboxes in AngularJS.

Template

<span ng-repeat="day in selectDays">
    <input type="checkbox" id="{{day}}" ng-model="selectedList[day]"/>
    <label for="{{day}}">{{day}}</label>
</span>
<button ng-click="submit()">Submit</button>

Scopes

//default states
$scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$scope.selectedList = {};

/**
 * Action
 */
$scope.submit = function () {
    angular.forEach($scope.selectedList, function (selected, day) {
        if (selected) {
           console.log(day);
        }
    });
};
like image 98
lin Avatar answered Sep 20 '22 01:09

lin