Retrieve the chosen checkbox items with a single button click

Is there a way to retrieve the ID of a checked checkbox item in a list when a button is clicked, and then store those items in a variable or array for future use?

Sample HTML:

<input id="btnCheck" type="button" value="Next" ng-click="addSelected()" />    
<div ng-controller="movieController">
        <ul>
            <li ng-repeat="movie in Movies">
                    <input id="chkBox-{{ movie.MovieID }}"
                         type="checkbox"
                         ng-checked="selection.indexOf(movie.MovieID) > -1"
                         ng-click="toggleSelection(movie.MovieID)"
                    />
            </li>
        </ul>
    </div>

Javascript:

$scope.AddSelected = function () {
    var selected = $scope.selection
    console.log(selected);
}

$scope.selection = [];
$scope.toggleSelection = function toggleSelection(movie) {
    var idx = $scope.selection.indexOf(movie);
    if (idx > -1) {
        $scope.selection.splice(idx, 1);
    }
    else {
        $scope.selection.push(movie);
    }
};

Answer №1

To enhance your filtering capabilities, consider creating a custom filter that will extract a selected value ID based on certain criteria. This filter requires two parameters: the first parameter checks for a condition, and if it is true, the second parameter property array will be returned from the filter.

Custom Filter Markup

<body ng-app="app">
  <div ng-controller="movieController">
    {{(Movies | returnPropertyWhenCheckedTrue: 'checked' :'MovieID')}}
    <ul>
      <li ng-repeat="m in Movies">
        <input id="chkBox-{{ m.MovieID }}" type="checkbox" ng-model="m.checked"/>
      </li>
    </ul>
  </div>
</body>

Explanation of the Filter

app.filter('returnPropertyWhenCheckedTrue', function() {
  return function(array, propertyToChecked, property) {
    var returnArray = [];
    angular.forEach(array, function(value, index) {
      if (value[propertyToChecked])
        returnArray.push(value[property]);
    });
    return returnArray;
  }
});

See the Working Example on Plunkr

Answer №2

To enable multiple selection, you can utilize ng-options. It is highly beneficial for this purpose;

<select name="movies" ng-model="selectedMovieIDs" 
ng-options="m.MovieID as m.MovieID for m in movies">

</select>

For more detailed information: ngOptions

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 Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

What are the steps to encapsulate an Android app within a React Native component, effectively creating a complete view?

I'm currently working on integrating my existing android native app into a React Native application with react-navigation. I'm trying to figure out how I can wrap the android app in a component and call it within the StackNavigator like this: co ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...

When a task hasn't been completed within a 3-second timeframe, execute a specific block of code

I need to incorporate a promise in my code to execute angular.bootstrap() in block 2 if 3 seconds have passed and angular.bootstrap() in block 1 has not been completed. I have two separate blocks of code: // block 1: Office.initialize = function (reason) ...

Strategies for selecting glyphs in SVG fonts based on their Unicode properties

My goal is to extract specific characters from SVG fonts created for music engraving. Music fonts typically include a large collection of characters (> 3500), but I only require a small subset of them for caching glyphs in compressed form to ensure quic ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

What is the correct way to navigate data through my Node.js API?

I am struggling with getting the JSON response to display at the /api/orders_count endpoint. Here is a breakdown of my setup: In my project, I have various files: Routes file - where the orders_count route is defined: routes/index.js const express = req ...

Leveraging class names to dynamically apply CSS styles to components based on their props value

In the process of developing a collection of reusable components, I have utilized material-ui and styled them with CSS. One specific requirement is to dynamically set the width of a component through a prop passed into a custom button. My goal is to lever ...

React encountered an unexpected end of JSON input while streaming JSON data

Currently, I am facing a challenge with streaming a large amount of data from a NodeJS server that retrieves the data from Mongo and forwards it to React. Due to the substantial volume of data involved, my approach has been to stream it directly from the s ...

Is it possible to rotate a Three.js group around a specific point within the group using Three.js?

Summary: The objective is to adjust the arrow's orientation around the circle. We have a function that introduces a shape (https://i.sstatic.net/l3lZB.jpg) (comprising of three Meshes) into the scene. By default, it points to the right, but we desire ...

Response received after an extended operation in HTTP

We are currently working on a project using Node.js along with the Expressjs framework. The application we are developing involves storing client/prospect information, with authenticated users having the ability to modify the database and trigger long-runn ...

Incorporating JSTree Into Your Website's Heading: A Step-By-Step

I'm in search of a way to integrate the following code snippet as a JSTree into the heading section of a webpage, depicted below: <div id="jstree"> <ul> <li>Core 1 <ul> & ...

Access to property 'nodeType' on AJAX request in Firefox has been denied due to permission error

On my webpage, I have integrated the Google Sign-in button along with gapi for interaction. After a successful authentication using the Google API, an AJAX call is made to the server using JQuery: var token = gapi.auth.getToken(); var data = { "to ...

saving data in an array using JavaScript

I have a requirement to store values into an array in HTML that are generated by a random number generator in Python as {{player.a1s1}}. I have successfully handled this part. Essentially, every time the button "mm1a" is clicked, a new button will be displ ...

I'm only seeing output on two of my input boxes - what's going on?

Currently in the process of learning JQUERY/HTML, I decided to create a shopping cart. My goal is to display the subtotal, tax, shipping costs, and total cost in input boxes. While I successfully displayed the sub total and shipping cost, I encountered an ...

Leveraging AJAX to call upon a designated php file

I have a selection of menu items on my webpage, each with different options: option1, option2, and option3. Additionally, I have corresponding PHP files on my server for each of these menu items: option1.php, option2.php, and option3.php. For simplicity, ...

Vue-Router failing to redirect in a Single Page Application using Vue and Laravel

I have been attempting to implement vue-router in a Vue.js/Laravel project. My project consists of two simple pages: home page: https://i.stack.imgur.com/GmHOR.png about page (single-page scrolling): https://i.stack.imgur.com/CZDnZ.png The files used ...

Remove search results in real-time

I'm currently working on implementing a search feature for a web application. While I have made some progress, I am facing an issue with removing items when the user backspaces so that the displayed items match the current search query or if the searc ...

Utilizing Three.js to showcase large 3D images from a JSON file

I am in need of showcasing 3D images. I have a .obj file that is 80 MB in size which I converted to a json file size of nearly 75 MB. While using three js, I managed to display a rotating 3D image, but the main issue is the loading speed, which currently t ...

Ways to evaluate negative numbers in JavaScript

I need to validate latitude and longitude values within the range of -180 to 180. If a number falls outside of this range, an error should be displayed. Below is the code I have written for this validation: if((markerPoint[0] && parseInt(markerPoint[0] ...