abc12345
abc12345

Reputation: 39

how should i deselect the chekbox that is already selected in html page using angularjs?

I have checkboxes in my html as follows,

<div ng-repeat="fruit in fruits">
    <input type="checkbox" name="{{fruit.name}} ng-model="fruit.value" 
         ng-checked="isChecked(fruit)" ng-change="changed(fruit)" ng-required="true" ">{{fruit.name}}
</div>
<input type="hidden" ng-model="selectedFruits"> 

And I have angular js code as follows,

    $scope.fruits=[{name:"Mango", value:false},{name:"Apple", value:false},{name:"Banana", value:false}];
var array=["Apple","Banana"];
$scope.isChecked = function(fruit){
     for(var I=0; I <array.length; I++){
              if(fruit.name == array[I]){
                 fruit.value=true;
              }
           }  
}
$scope.changed= function(fruit){
   var selectFruit ='';
   $scope.fruits.forEach(function(fruit){   
      if(fruit.value){
         if(selectFruit){
            selectFruit += '-';
         }
         selectFruit += fruit.name;
      }
   })
   $scope.selectedFruits = selectFruit;
}

And that hidden field is for appending the selected checkboxes name in "selectedFruits ". [Ex. Mango-Apple]

From above code I'm getting by default selected checkboxes in html page as Apple and Banana that is in an array.

My question is when I'm trying to deselect that checkboxes (Apple/banana), it does not gets deselected . It always shows selected only. How should I deselect that checkboxes? Can someone please help me?

Upvotes: 1

Views: 70

Answers (1)

Rakesh Chand
Rakesh Chand

Reputation: 3113

Make some changes in HTML:
Here

<div ng-repeat="fruit in fruits">
    <input type="checkbox" name="{{fruit.name}} ng-model="fruit.value" 
         ng-click="isChecked(fruit)" required>{{fruit.name}}
</div>
<input type="hidden" ng-model="selectedFruits"> 

EDIT

var array=["Apple","Banana"];
   for(var I=0; I <array.length; I++){
      if(fruit.name == array[I]){
         fruit.value=true;
      }
   }  

Put this content outside the checked function or create a new function and put this code in that and call it wherever you want

EDIT-2

selectAppleBanana();
function selectAppleBanana(){
  for(var I=0; I <array.length; I++){
     for(var J=0;J<$scope.fruits;J++){
         if($scope.fruits[J].name == array[I]){
            $scope.fruits[J].value=true;
         }
     }
   }    
}
$scope.isChecked = function(fruit){
   //don't call it here otherwise it won't get deselected ever
   //selectAppleBanana();
   var selectFruit ='';
   $scope.fruits.forEach(function(fruit){   
      if(fruit.value){
         if(selectFruit){
            selectFruit += '-';
         }
         selectFruit += fruit.name;
      }
   })
   $scope.selectedFruits = selectFruit;
}

Upvotes: 1

Related Questions