Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get checkbox value in angularjs?

I have a 10(or n)checkbox in my ng-view. Now I would like to ask here that What is the most efficient or simple way to check if checkbox is checked and if checked get the value of checkbox.

<ul>
  <li ng-repeat="album in albums">
   <input type="checkbox" ng-model="folder.Selected" value={{album.name}} />
   </li>
  </ul>

I have ng-controller(getAlbumsCtrl), in that I have an array in which I want to push all the checkedbox albums names into albumNameArray

like image 327
Kgn-web Avatar asked Jun 27 '15 16:06

Kgn-web


People also ask

How do you find checkbox is checked or not in AngularJS?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.

How do you pass checkbox value 0 if not checked and 1 if checked angular?

Add a hidden input that has the same name as the checkbox with the value of 0 BEFORE the checkbox. If the checkbox is unchecked, the hidden field value will be used, if it is checked the checkbox value will be used.

How do I check if a checkbox is checked in angular 8?

Just define an ng-model directive in the checkbox and to find checkbox checked or not check model return value (TRUE or FALSE). If it has TRUE means checkbox is been checked.

How do you check checkbox is checked or not in TypeScript?

To check if a checkbox element is checked in TypeScript: Type the element as HTMLInputElement using a type assertion. Use the checked property to see if the element is checked. The property will return true if it is checked and false otherwise.


1 Answers

You can loop over the array to find out which is selected and push into the name array.

<ul>
  <li ng-repeat="album in albums">
    <input type="checkbox" ng-model="album.selected" value={{album.name}} />
  </li>
</ul>

$scope.save = function(){
  $scope.albumNameArray = [];
  angular.forEach($scope.albums, function(album){
    if (!!album.selected) $scope.albumNameArray.push(album.name);
  })
}

// alternatively you can use Array.prototype.filter on newer browsers (IE 9+)
$scope.save = function(){
  $scope.albumNameArray = $scope.albums.filter(function(album){
    return album.selected;
  });
}

jsbin

like image 112
Icycool Avatar answered Oct 30 '22 07:10

Icycool