Transmitting the values of my CheckBox list to a JSON file

Here is an interesting question that I have encountered. I created a drop box list using ng-repeat. Take a look at the code below:

 <ul>
 <li ng-repeat="item in formLIST.ContractType">
    <input type="checkbox" ng-click="checkItems(item)" value={{item.ls_ItemIndex}} >{{item.ls_ItemValue}}
 </li>
 </ul>

This is my AngularJS code snippet:

$scope.listitem=[];
$scope.checkItems = function (item) {
    $scope.listitem.push({
        item: item.ls_ItemValue      
    });

I have a query regarding this setup: I would like to know how to ensure that when the checkboxes are checked or unchecked, it correctly adds or removes the corresponding value in my JSON file.

Currently, clicking on the checkboxes results in adding them to my JSON file. However, if I uncheck and check them again, they get added multiple times without being removed. My goal is to add these values only once.

Answer №1

Displayed below is the function:

$scope.checkItems = function (item) {
    var idx = $scope.listitem.indexOf(item.ls_ItemIndex);

    if(idx == -1) // item not currently selected
       $scope.listitem.push(item.ls_ItemIndex);
    else // item already selected
       $scope.listitem.splice(idx,1);
}

Answer №2

I suggest utilizing ng-model for this task:

<ul>
 <li ng-repeat="item in formLIST.ContractType">
    <input type="checkbox" ng-model="item.Is_ItemValue" />{{item.ls_ItemValue}}
 </li>
 </ul>

  <!-- selected list -->
  <ol>
  <li ng-repeat="item in formLIST.ContractType | filter: {Is_ItemValue:true}"> {{ item }}</li>
  </ol>

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

The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; v = inflater.inflate(R.layout.webview_l ...

Encountering Zip File Corruption Issue post MongoDB Download

My goal is to attach a zip file to an object and request the zip file when the object is called from the client. I was successful in uploading the zip file using the following code: const upload = multer({ fileFilter(req, file, cb){ if (!file. ...

Sort an array of strings with binary search and insert a new string

My current challenge involves working with an alphabetically sorted array of strings: let collection = ["ABC", "BCD", "CAB", "FGH", "JKL", "ZKL"]; The task at hand is to insert the string "CQW" into the collection while maintaining the sorted order witho ...

Is it possible to observe the website functionalities and execute them directly from the console?

Question about JavaScript: Is it safe for a script tag to be visible in the body of the developer console and for functions to be run directly on the website? It raises security concerns, and there should be measures in place to prevent this kind of displa ...

Exploring advanced mathematical calculations in QtQuick Qml with JavaScript for handling large numbers

I need to calculate the orbit of the Sun around the Galaxy. The mathematical formula I am using is ((241828072282107.5071453596951 * 666) * 2) * 3.14159265359. In QML JavaScript, I received the answer 1011954093357316100, but the correct answer is 10119540 ...

Emitting events to multiple components in VueJS with different parent components

I have multiple Vue Components set up like this: App.js | |-- CreateTasks | |-- LatestTasks (displays 20 tasks) | |-- FooBar | |---LatestTasks (displays 10 tasks) My goal is to trigger an event from the CreateTasks component when a new task is c ...

Adding information to an array within a document in a MongoDB database

I am facing an issue where I am trying to add data to the readBook array in my User collection document. The code and console.log seem to indicate that the User is retrieved from the database and there is data to push, but nothing changes after the code ex ...

What is the best way to create a Promise that is fulfilled when an event is emitted by an event emitter in JavaScript or Node.js?

Is there a way to create a Promise in Node JS that will only resolve when a specific event is emitted by an event emitter? I am trying out the following code snippet, but I am unsure how to make the promise wait until the event occurs. function bar(resol ...

Add .json files to your database

After successfully downloading tweets into a json file, the next step is to import it into a database using the following function: def import_json(fi): logging.warning("Loading tweets from json file {0}".format(fi)) for line in open(fi, "rb"): data ...

If the server goes offline, it will not produce an error message

Running a factory in AngularJS angular.module('app.services',[]) .factory('myFactory', function($http){ return { getData: function(){ return {animal: 'dog'} }, isUser: function() ...

Employed AJAX for webpage updates, but seeking guidance on URL modification

I recently followed a tutorial on AJAX from http://www.w3schools.com/ajax/default.asp Currently, I am using this knowledge to update my page asynchronously. However, I also want the URL to be dynamically generated based on the new content. When a user cl ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

Create a duplicate <li> element and animate it using jQuery

Here are the list items: <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</l ...

Is it possible for a recursive function in expressjs to return an empty array?

I am working on extracting all child elements from MongoDB using a recursive function. The function loops through all the values and successfully logs them when pushed to an array. However, I am facing an issue where the returned array is empty. This cod ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

JavaScript - Deleting the last element of an array

I have currently integrated a third-party API to visualize data using Highcharts. This external API provides data specific to the current month, such as March, April, May, and so on. graphArrOne contains an array with 251 elements. graphArrTwo contains ...

Exploring Passportjs Callbacks and parsing arguments

I'm struggling to grasp the concept behind the custom callback in Passport.js. I'm not sure why it requires (req, res, next) at the end. Shouldn't these values be obtained from closure? app.get('/login', function(req, res, next) { ...

My regular simple form is experiencing issues with AngularJS and jQuery functionality

I am currently expanding my knowledge in AngularJS and have created a simple form. However, as a PHP developer, I decided to utilize PHP as the server-side scripting language. I am encountering difficulties in submitting the data to the server, despite try ...

Adding data to Vue with Pug: A comprehensive guide

Is there a way to localize a component using vue-loader with single-file components and a .pug template? Here's an example: <template lang="pug"> div.container {{ test }} div.content h1 Proof of concept app b Vue.js + Type ...

Styling with the method in React is a beneficial practice

I am working on a simple React app that includes some components requiring dynamic styling. I am currently using a method to achieve this, but I am wondering if there are other recommended ways to handle dynamic styling in React. Everything seems to be wor ...