简体   繁体   English

从选中的复选框获取数据

[英]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. 我正在做的是从api获取数据并显示为复选框。 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. 我只使用Javascript和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. 然后,您可以根据示例中给定值的名称对其进行检查,选中该复选框时,其value1value2都将作为属性。

The documentation seems pretty straight forward. 该文档似乎很简单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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