Snopzer
Snopzer

Reputation: 1692

angularjs get only selected checkbox

i want to get the selected checkboxes in my loop, for that check box i have to retrive the amount field onclick.

Here is my HTML script :

<div ng-repeat="$item in items">
    Amount  :<input ng-model="$item.daily_data.payment_amount">
    Check  : <input type=checkbox ng-model="checkAmount[$item.daily_data.id]" ng-value="$item.id" >
</div>

<input type="button" ng-click="checkNow()" />

The below script showing all check boxes . i want the only selected one.

JS Script :

$scope.checkAmount = {};
$scope.checkNow(){
console.log($scope.checkAmount);
}

Upvotes: 2

Views: 2620

Answers (1)

developer033
developer033

Reputation: 24864

First of all to use functions with $scope you should do something like this:

$scope.checkNow = function() {
  ...
}

or

$scope.checkNow = checkNow;

function checkNow() {
  ...
}

About your problem:

You could bind the checkboxes to a property (something like checked), so you can have the items that are checked easily in your controller.

Then, to calculate the total of all checked amount , I' suggest you to use Array.prototype.filter() + Array.prototype.reduce().

Here's a demo based on your original code:

(function() {
  angular
    .module("app", [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.checkNow = checkNow;
    $scope.checkAmount = {};
    $scope.items = [
      {
        "id": 1
      }, 
      {
        "id": 2
      },
      {
        "id": 3
      }
    ];

    function checkNow() {
      $scope.total = $scope.items.filter(function(value) {
        return value.checked;
      }).reduce(function(a, b) {
        return a + b.amount;
      }, 0);
    }
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-repeat="$item in items">
    <label>
      Amount: <input type="number" ng-model="$item.amount">
    </label>
    <label>
      Check: <input type=checkbox ng-model="$item.checked">
    </label>
  </div>

  <button type="button" ng-click="checkNow()">Check now</button>
  <hr>
  <label for="total">Total</label>
  <input type="number" id="total" disabled ng-model="total">
</body>

</html>

Upvotes: 3

Related Questions