Allow only One (Single) CheckBox to be checked at a time in AnularJS

Last Reply one month ago By dharmendr

Posted one month ago

How to check checkbox only one at a time, if an user is clicking on any of the checkbox, it is checked, if that user wants to check another chechkbox, the another checkbox is checked, but the previously checked checkbox is unchecked automatically.

    $scope.divisions = null;
    $http.get(apiUrl + "/api/Warehouse/getAllDivisions")
    .then(function (response) {
        $scope.divisions = JSON.parse(response.data);
        $scope.check = function (index) {
            for (var i = 0; i < $scope.divisions.length; i++) {
                if ($scope.divisions[i].DIVISIONID != index) {
                    $scope.divisions[i].hasChecked = false;
                }
            }         
            if ($scope.divisions[index].hasChecked) {                   
                $scope.divisionMachines = null;
                $http.get(apiUrl + "/api/Warehouse/getDivisionMachines?DivisionId=" + $scope.divisions[index].DIVISIONID + "")
                .then(function (response) {
                    $scope.divisionMachines = JSON.parse(response.data);
                })
            } 
        }
    })

 

<button class="accordion" ng-click=""><b>SEARCH BY DIVISION</b></button>
    <div class="panel" style="margin-top: 1rem">
        <table>
            <tr ng-repeat="div in divisions">
                <td><input type="checkbox" class="" ng-change="check($index)" ng-model="div.hasChecked"></td>
                <td style="padding-left:5px">{{div.DIVISION}}</td>
            </tr>
         </table>
    <br />
</div>
Posted one month ago

Hi skp,

Check this example. Now please take its reference and correct your code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script type="text/javascript">
        var app = angular.module("MyApp", []);
        app.controller("MyController", function ($scope) {
            $scope.divisions = [{ DIVISION: "Div 1" }, { DIVISION: "Div 2" }, { DIVISION: "Div 3"}];
            $scope.check = function (division) {
                for (var i = 0; i < $scope.divisions.length; i++) {
                    if ($scope.divisions[i].DIVISION != division) {
                        $scope.divisions[i].hasChecked = false;
                    }
                }
            }
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <table>
        <tr ng-repeat="div in divisions">
            <td>
                <input type="checkbox" class="" ng-change="check(div.DIVISION)" ng-model="div.hasChecked" />
            </td>
            <td style="padding-left: 5px">
                {{div.DIVISION}}
            </td>
        </tr>
    </table>
</body>
</html>

Demo