简体   繁体   中英

Get data from a checked checkbox

I need to get the info from a checked checkbox. What i'm doing is get data from an api and showing as checkbox. Here's a part of my code where also have a validation if at least one coupon is checked:

vm.sendData = function() {
  vm.apiData = couponApi.get({
    idOrder: vm.idOrder
  })
  .$promise
  .then(function(data) {
    for (var i = 0; i < data.Response.length; i++) {
      data.Response[i].Select = vm.all;
    }
    vm.coupons = data.Response;
    vm.combo = data.Response.length > 0;
  });
}

vm.selectAll = function() {
  vm.all = !vm.all;
  vm.coupons.forEach(function(o) {
    o.Select = vm.all;
  })
}

vm.submit = function() {
  var checked = 0;
  vm.coupons.forEach(function(o) {
    if (o.Select === true)
      checked += 1;
  })
  if (vm.all || checked > 0) {} else if (checked === 0) {
    alert("Select at least one coupon");
  }
}

How can i get the value of the checked checkbox? I'm using only Javascript and AngularJs.

You need to set the checked value when you instantiate the control like this:

angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.checkboxModel = {
       value1 : true,
       value2 : 'YES'
     };
    }]);

Then you can check it based on the name you gave the value in the example the checkbox will have both value1 and value2 as properties when checked.

The documentation seems pretty straight forward.

source: https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM