2

I am working on a school project where a user can choose what items he/she can borrow from the school's computer services office. I have completed the application form where the student/faculty can insert their profile information. I am having issues regarding the checkboxes in AngularJS.

I need to total/sum up the IDs of the checkboxes so that it can be inserted into the database as a single int, not an array. Here are the code and some information.

        $scope.chkItems = [
        {
            id: 1,
            name: 'Laptop',
            value: null,

        }, {
            id: 2,
            name: 'Headset',
            value: null
        }, {
            id: 4,
            name: 'Projector',
            value: null
        }, {
            id: 8,
            name: 'Tablet',
            value: null
        }, {
            id: 16,
            name: 'Speakers',
            value: null
        }];



$scope.save = function () {

                var chkItemsValue = '';

                $scope.chkItems.forEach(function (Item) {

                    if (Item.value) {
                        chkItemValue +=  chkItem.id;
                    }
                })   
                
                }
<md-input-container class="md-block" flex-gt-sm>
<label class="force-input-label">Items</label>
</br>
<div ng-repeat="chkItem in chkItems">
<md-checkbox name="chkItem.name" ng-model="chkItem.value" ng-true-value=1 ng-false-value=0>{{chkItem.name}}
</div>
</md-input-container>

I can insert the value on the database but the value is different instead of getting the total the value I get an array like output.

  • Currently, I am getting this:

if I check {Laptop, Projector, Speakers} the total would be 1416

  • What I want:

if I check {Laptop, Projector, Speakers} the total would be 21

I am new to AngularJS and web development. Your inputs are greatly appreciated!

ThankYOU!

0

1 Answer 1

0

Quick answer, don't initialise your counter as a string

var chkItemsValue = 0 // not ''

Array.prototype.reduce answer

var chkItemsValue = $scope.chkItems.reduce((count, item) => {
    return count + (item.value ? item.id : 0)
}, 0)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your quick reply. : )
Thanks for your quick reply. : ) WOW. it took me days to check on this one. And i checked my old code the chkItemsValue is set to zero. Maybe it was change when i use find and replace. THANKS A LOT. This matter has already been resolved thankyou!

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.