4

I display my checkbox list using this code :

 <ion-checkbox ng-repeat="item in listPref"
   ng-model="item.checked" ng-checked="item.checked">
   {{ item.text }}
 </ion-checkbox>

This is my listPref:

 $scope.listPref = [
    {text: 'Cinema'},
    {text: 'Sport'},
    {text: 'It'} ,
    {text: 'Music'},
    {text: 'Theater'},
    {text: 'Conference'}];

I try this code to get the text of all selected item

 for(var i =0 ; i <$scope.listPref.length ; i++){
console.log($scope.listPref[i].checked.text); 
 } 

I get the message undefined Cannot read property 'text' of undefined at Scope.$scope.pref in my console. Can someone help me please.

1 Answer 1

8

HTML:

<ion-content>
   <ion-checkbox ng-repeat="item in listPref"
       ng-model="checkItems[item.text]" ng-change="print()">
       {{ item.text }}
   </ion-checkbox>
   <button type="button" name="button" ng-click="save()">Save</button>
</ion-content>

JS (inside controller):

$scope.listPref = [
    {text: 'Cinema'},
    {text: 'Sport'},
    {text: 'It'} ,
    {text: 'Music'},
    {text: 'Theater'},
    {text: 'Conference'}
];

$scope.checkItems = { }

$scope.print = function() {
    console.log($scope.checkItems);
}

$scope.save = function() {
    var array = [];
    for(i in $scope.checkItems) {
        console.log($scope.checkItems[i]);
        if($scope.checkItems[i] == true) {
            array.push(i);
        }
    }
    console.log(array);
}

You can do whatever you want with the values. print() just prints the object of all the values currently checked or unchecked (true/false). save() stores the value of the checked checkbox inside an array and then prints the array. You can do whatever you like with the values, this example stores them in an array and prints to the console so what is happening can easily be seen.

Comment if you have any questions.

Sign up to request clarification or add additional context in comments.

6 Comments

thnkx, it works perfectly. But i would get only the text value to store it in my database,I try ` console.log($scope.checkItems[i].text );` i get the error undefined. thank your answer.
What are you storing into the database and how are you storing it? Value by value, array, object, etc?
Also, checkItems is an object where they key is the text that is in the checkbox. { Cinema: true, Sport: false }. There is not a property called "text" as you are trying to reference it.
i wd store it by object
Then just store checkItems, it'll have true or false values for each checkbox that was clicked. If it was never clicked it will not be inside the object, but that is about the same as being false.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.