How to check if checkbox is selected/checked in this Angular example? So when user select/check first check box I want to get true and when unselect/uncheck it I want false.
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.toggleSelection = function toggleSelection() {
// how to check if checkbox is selected or not
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Controller">
<h1>Get checkbox selection (true/false)</h1>
<label>
<input id="one" type="checkbox" ng-click="toggleSelection()">This
</label>
<br>
<label>
<input type="checkbox" ng-click="toggleSelection()">That
</label>
<br>
<label>
<input type="checkbox" ng-click="toggleSelection()">Lorem
</label>
<br>
<label>
<input type="checkbox" ng-click="toggleSelection()">Ipsum
</label>
</div>
It works:
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.toggleSelection = function toggleSelection(event) {
// how to check if checkbox is selected or not
alert(event.target.checked);
};
})
<!DOCTYPE html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Controller">
<h1>Get checkbox selection (true/false)</h1>
<label>
<input type="checkbox" ng-click="toggleSelection($event)"> This
</label>
<br>
<label>
<input type="checkbox" ng-click="toggleSelection($event)"> That
</label>
<br>
<label>
<input type="checkbox" ng-click="toggleSelection($event)"> Lorem
</label>
<br>
<label>
<input type="checkbox" ng-click="toggleSelection($event)"> Ipsum
</label>
</div>
</body>
</html>
I would suggest that you use ng-model
instead.
<input type="checkbox" ng-model="checkbox1">
Then in your controller $scope.checkbox1
will be true or false based on if the checkbox is checked or not.
if($scope.checkbox1){
//Checkbox is checked
} else {
//Checkbox is not checked
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With