Search code examples
javascriptjqueryangularjscheckboxangularjs-ng-disabled

Angularjs checkbox checked enables input field


I'm kinda new in AngularJS and my issue is:

I have a loop like this:

 <body ng-app="ngToggle">
    <div ng-controller="AppCtrl">
        <input type="checkbox" ng-repeat="btn in btns" class="here" value="{{btn.value}}">

        <input type="text" class="uncheck" disabled>
    </div>
</body>

One of those checkboxes has a value of "OTHER", and what I need to do is: when the checkbox with the "OTHER" value is checked it remove the disabled attribute from the <input type="text" class="uncheck" disabled>

This is my controller:

angular.module('ngToggle', [])
    .controller('AppCtrl',['$scope', function($scope){
        $scope.btns = [
        {value:'one'},
        {value:'two'},
        {value:'other'}
        ];
}]);

Hope someone can help me, Thanks.


Solution

  • Use ng-change directive and test value of other checkbox in forEach-loop

    angular.module('ngToggle', [])
      .controller('AppCtrl', ['$scope',
        function($scope) {
          $scope.disabled = true;
          $scope.btns = [{
            value: 'one'
          }, {
            value: 'two'
          }, {
            value: 'other'
          }];
          $scope.onChange = function() {
            $scope.btns.forEach(function(btn) {
              if (btn.value === 'other' && btn.status === true) {
                $scope.disabled = false;
              } else {
                $scope.disabled = true;
              }
            });
          }
        }
      ]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="ngToggle">
      <div ng-controller="AppCtrl">
        <input type="checkbox" ng-repeat="btn in btns" class="here" ng-model='btn.status' ng-change='onChange()'>
    
        <input type="text" class="uncheck" ng-disabled='disabled'>
      </div>
    </body>