Creating an array of objects through checkbox validation in AngularJS

$scope.data = [{
            'id': '1',
            'itemName': 'mousepad',
            'price': '20'
        }, {
            'id': '2',
            'itemName': 'keyboard',
            'price': '20'
        }, {
            'id': '3',
            'itemName': 'charger',
            'price': '20'
        }]

$scope.checkedTrue = function(h) {
            $scope.demoArr = [];
            $scope.demo = [];
            $scope.demoArr.push(h);

            function check() {

                var deee = $.grep($scope.demoArr, function(record) {
                    console.log('iijjdkkdkkdkd======>', record);

                    return record
                });

                $scope.checkDemo = deee;
            }
            check();
            $scope.demo.push($scope.checkDemo);
        };
<table class="table m-t-30">
  <thead>
    <tr>
      <th>#</th>
      <th>ItemName {{selected}}</th>
      <th>ItemPrice</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="tic in data track by $index">
      <td>
        <input id="checkbox2" type="checkbox" ng-model="selected[tic.id]" ng-change="checkedTrue(tic)"/>
      </td>
      <td><span>{{tic.itemName}}</span></td>
      <td><span>{{tic.price}}</span></td>
    </tr>
  </tbody>
</table>

I currently have an array displayed using ng-repeat:

var data = [{
            'id': '1',
            'itemName': 'mousepad',
            'price': '20'
        }, {
            'id': '2',
            'itemName': 'keyboard',
            'price': '20'
        }, {
            'id': '3',
            'itemName': 'charger',
            'price': '20'
        }];

In each row, there are checkboxes. When a user checks a checkbox, I want to extract that particular row object and add it to a new array.

For example:

Add only checked objects into another array named Checked

var Checked = [{
            'id': '1',
            'itemName': 'mousepad',
            'price': '20'
         },{
        'id': '3',
        'itemName': 'charger',
        'price': '20'
    }];

If the user unchecks a checkbox, I want to remove the corresponding object from the Checked array.

If the checkbox is checked again, the object should be added back to the Checked array.

Answer №1

1- Utilize the ng-click attribute to execute a function

2- Establish an array containing checked checkboxes

3- Whenever any checkbox is altered, check the array for the presence of the item and either add or remove it from the array

Here is a straightforward example

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.data = [{
      id: "1",
      itemName: "mousepad",
      price: "20"
    },
    {
      id: "2",
      itemName: "keyboard",
      price: "20"
    },
    {
      id: "3",
      itemName: "charger",
      price: "20"
    }
  ];
  $scope.tempModel = '';
  $scope.checkedArray = [];

  $scope.updateCheckArray = function(itm) {
    let index = $scope.checkedArray.findIndex(function(r) {
      return r.id == itm.id;
    });
    if (index == -1) {
      $scope.checkedArray.push(itm);
    } else {
      $scope.checkedArray.splice(index, 1);
    }
  };
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <hr>
    <div class="post-content" ng-repeat="d in data">
      <input ng-click="updateCheckArray(d)" type="checkbox" ng-model="tempModel" />{{d.itemName}}
      <hr>
    </div>

    {{checkedArray}}

  </div>
</body>

</html>


Update

1- Modify function body as follows

  $scope.checkedTrue = function(itm) {
    let index = $scope.checkedArray.findIndex(function(r) {
      return r.id == itm.id;
    });
    if (index == -1) {
      $scope.checkedArray.push(itm);
    } else {
      $scope.checkedArray.splice(index, 1);
    }
  };

2- Include an empty array for selected items and initialize an empty model

$scope.tempModel = "";
$scope.checkedArray = [];

Adjustments specific to your code:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.data = [{
      id: "1",
      itemName: "mousepad",
      price: "20"
    },
    {
      id: "2",
      itemName: "keyboard",
      price: "20"
    },
    {
      id: "3",
      itemName: "charger",
      price: "20"
    }
  ];
  $scope.tempModel = "";
  $scope.checkedArray = [];

  $scope.checkedTrue = function(itm) {
    let index = $scope.checkedArray.findIndex(function(r) {
      return r.id == itm.id;
    });
    if (index == -1) {
      $scope.checkedArray.push(itm);
    } else {
      $scope.checkedArray.splice(index, 1);
    }
  };
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <hr>
    <table class="table m-t-30">
      <thead>
        <tr>
          <th>#</th>
          <th>ItemName {{selected}}</th>
          <th>ItemPrice</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="tic in data track by $index">
          <td>
            <input id="checkbox2" type="checkbox" ng-model="tempModel" ng-change="checkedTrue(tic)" />
          </td>
          <td><span>{{tic.itemName}}</span></td>
          <td><span>{{tic.price}}</span></td>
        </tr>
      </tbody>
    </table>

    {{checkedArray}}

  </div>
</body>

</html>

Answer №2

Feel free to review the code snippet in the provided fiddler link

Fiddle Link

<div ng-app>
  <h2>To-Do List</h2>
  <div ng-controller="TodoCtrl">
    <ul>
      <li ng-repeat="item in data">
        <input type="checkbox" value="{{item.id}}" ng-click="addTo($event)">
        {{item.itemName}}
      </li>
    </ul>
    <br>
    <h4>
    Added Items
    </h4>
    {{itemArray}}
  </div>
</div>;

function TodoCtrl($scope) {
  $scope.data = [{
            'id': '1',
            'itemName': 'mousepad',
            'price': '20'
        }, {
            'id': '2',
            'itemName': 'keyboard',
            'price': '20'
        }, {
            'id': '3',
            'itemName': 'charger',
            'price': '20'
        }];
     $scope.itemArray = [];   
    $scope.addTo = function(event){
        if(event.currentTarget.checked){
            $scope.itemArray.push(this.item)
      }else{
                $scope.itemArray.pop(this.item)         
      }
    }    
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the discrepancy in the first and second socket request in my Node.js code?

Below is my echo server code snippet var net = require('net') var server = net.createServer(function(socket) { socket.write('Echo server\r\n'); socket.on(&ap ...

Unable to access the 'fn' property of undefined in Handlebars causing a TypeError

I encountered an issue with my custom handlebars helper. When I fail to define values for the parameters, I receive the following error message. module.exports = function(src, color, classatr, options) { if (typeof src === 'undefined') src ...

Bringing together a dual $exists in a MongoDB search

I'm trying to locate documents that have certain fields using the $exists operator. Specifically, I am focusing on two fields: payload.fields.MDI_CC_DIAG_DTC_LIST and payload.asset. If I only want to find documents with the first field, I execute thi ...

The object3d.translateZ function in Three.js is resulting in unexpected NaN values for all position properties

I'm encountering an issue where the use of translate[X|Y|Z] on my object results in its position becoming distorted and only displaying NaN values. Using Three.js r70 The relative position differs from the absolute position: Snippet from my code i ...

Once all the asynchronous $http calls have finished loading, bring up the Template/Controller route

At this time, my index.html file contains the following: <div ng-controller="MainCntl"> <div ng-view></div> </div> The ng-view directive is responsible for loading either "template1.html" or "template2.html" based on the rou ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

Is there a way to display the value of a script function within an HTML block in an Angular application?

I need assistance displaying the "timeStops" value in an HTML block using a script. The "timeStops" output is in array format and I would like to showcase this array value within an HTML block. Here is the output of timeStops: [ "21:00", " ...

Struggling to retrieve JSON data from MYSQL database to Android App? Reach out for assistance with

I'm currently working on an Android application that interacts with a remote MYSQL database to retrieve information using JSON data. One of the challenges I'm facing is implementing a search functionality based on the userID in the app, and then ...

Stop the form from refreshing upon submission using an Ajax call in AngularJS

Currently, I am in the process of developing a search form that requires two inputs: Job title and Location. These keywords are used to gather data from various websites. However, upon submitting the form, the page refreshes itself. To prevent this, I have ...

Guide to configuring a background image from the public folder in a React application using Create React App

How do I properly set a background image in a .css file located in the src folder? src/Components/Component/Comp.css .services { background-image : url("./images/img-2.jpg"); background-position: center; background-size : cover; b ...

PHP - Struggling to insert data in the appropriate time format

Currently working on a scheduling program and looking to utilize Ajax for inserting hours into my database. When hardcoding the insertion, everything works perfectly fine. However, when using an array, it seems like json is altering the data - causing the ...

Error: The function row.child.hasClass is not a recognized function

My challenge is creating row details for DataTables without using Ajax. I have implemented something like this: $(document).ready(function () { function format ( name, value ) { return '<div>Name: ' + name + '<br /> ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

Firebase failed to load due to a redirected error occurring

Currently, I am in the process of learning ajax even though I haven't delved into a back-end language yet. To practice, I've decided to use Firebase from Google and run my code through localhost:8000 using Python 2.7. The server I am trying to GE ...

Customizing a tinyMCE button with a unique icon

I'm attempting to insert a Font-Awsome icon into a button that I included in tinyMCE using the following code: ed.addButton('youtube', { title: 'Add Video' , icon: 'icon-youtube', onclick: function () { ...

What is the most effective method for triggering individual sounds when hovering and clicking?

Hello everyone! I must admit, I am quite new to JavaScript and don't have much knowledge about it. I've shared my question on Reddit as well, so I'm hoping to get some guidance there too. Currently, I am working on editing a website and I w ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Efficiently transferring a style property to a child component as a computed property in Vue.js

Currently, I am facing an issue that involves too much logic in my inline style, which I would like to move inside a computed property. While I understand that this is the correct approach, I am unsure of how to implement it. To provide a clearer understa ...

Issue encountered when attempting to retrieve elements within an HTA's IFrame

We are currently working on automating an Intranet site using HTA and JavaScript. To bypass the browser security settings, we have implemented an Iframe within the HTA itself instead of opening the site in a browser. Despite being able to successfully logi ...

Customizing URLs in AngularJS using ui-router allows for more personalized

Hey there, I've encountered an issue with my app. Users can sign up as merchants and have their own store name with a URL structure like this: http://localhost:8000/#/storename The problem arises when the default homepage subpages, such as contactus ...