Retrieving the Value of a Checked Checkbox in Angular

I'm having trouble retrieving the selected item from an input checkbox.

<ul>
  <li ng-repeat='shoe in shoebox'>
    <input type='checkbox' ng-model='shoe.selected' id='shoe-{{shoe.name}}'>
    <label for='shoe-{{shoe.name}}'>{{shoe.name}}</label>
  </li>
  <button ng-click='whatIsChecked(shoe.selected)'>Apply</button>
</ul>

Then in my controller:

$scope.whatIsChecked = function(selectedThing) {
  console.log(selectedThing);
};

The above code is returning undefined.

Although the list items are being displayed correctly, it seems that the ng-model isn't storing the value of shoe.name or the checked item.

Answer №1

the variable shoe is only valid within the ng-repeat loop.

If you want to access what has been selected, you should consider using the filter method.

Update: If the selected property is not available, you can store the selected items in a separate array by triggering the ng-click event.

Please refer to the code snippet below:

angular.module("app", [])
  .controller("myCtrl", function($scope) {
  
    $scope.checkedShoes = [];
    
    $scope.shoebox = [{
        name: 'shoe1'
      },
      {
        name: 'shoe2'
      },
      {
        name: 'shoe3'
      },
      {
        name: 'shoe4'
      }
    ];
    
    $scope.save = function(e, shoe) {
      if (e.target.checked) {
        $scope.checkedShoes.push(shoe);
      } else {
        var index = $scope.checkedShoes.indexOf(shoe);
        if( index > -1) {
          $scope.checkedShoes.splice(index, 1);
        }
      }
      
    };
    
    $scope.whatIsChecked = function() {
      //var selected = $scope.shoebox.filter(function(item) {
      //  return item.selected === true;
      //});
      
      console.log($scope.checkedShoes);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" , ng-controller="myCtrl">
  <ul>
    <li ng-repeat='shoe in shoebox'>
      <input type='checkbox' ng-click="save($event, shoe)" id='shoe-{{shoe.name}}'>
      <label for='shoe-{{shoe.name}}'>{{shoe.name}}</label>
    </li>
    <button ng-click='whatIsChecked()'>Apply</button>
  </ul>
</div>

Answer №2

You can easily retrieve the selected items by using an angular.forEach loop, especially when dealing with multiple checked items.

$scope.checkedItems = [];
        angular.forEach($scope.shoebox, function(value, key) {
          if (value.selected)
            $scope.checkedItems.push(value.name);
});

Check it out:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.shoebox = [{
    name: 'Reboke',
    selected: false
  }, {
    name: 'woodlands',
    selected: false
  }, {
    name: 'Nike',
    selected: false
  }, {
    name: 'Fila',
    selected: false
  }];
  $scope.checkedItems = function() {
    $scope.checkedItems = [];
    angular.forEach($scope.shoebox, function(value, key) {
      if (value.selected)
        $scope.checkedItems.push(value.name);
    });

  }
});
<html>
<head>
  <meta charset="utf-8" />
  <title>AngularJS </title>
  <link rel="stylesheet" href="style.css" />
  <script src="https://code.angularjs.org/1.4.7/angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
  <ul>
  <li ng-repeat='shoe in shoebox'>
    <input type='checkbox' ng-model='shoe.selected' id='shoe-{{shoe.name}}'>
    <label for='shoe-{{shoe.name}}'>{{shoe.name}}</label>
  </li>
  <button ng-click='checkedItems()'>Apply</button>
   Checked items are: {{checkedItems}}
</ul>
     
</body>
</html>

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

How can I prevent duplicate IDs when submitting a form through AJAX within a while loop?

While submitting a form using Ajax within a while loop, I encountered an issue where the same form ID is being used multiple times due to the loop. As a result, the form only submits once. I believe that I need to generate a unique ID for each iteration of ...

Confirm the textarea in a form using jQuery

I am working on creating a plugin for an app that allows users to invite their friends via email, similar to how Dropbox offers extra space for referrals. As a newcomer to JQuery, I'm attempting to validate the single textarea field in my form before ...

`Receiving JSON data using AngularJS and Ionic: Fixing Errors`

Unable to display small JSON data from the server on an HTML file. Spent hours trying to troubleshoot but no luck. Any suggestions or ideas? Thank you for your help. JS File: (function() { var app = angular.module('myreddit', ['ionic&apos ...

Utilizing Bootstrap's Multi-Grid System

I am currently working on implementing a Bootstrap grid design that resembles pic1.jpg. However, I am facing challenges in achieving the desired layout, as pic2.jpg shows the current scenario. Below, I have shared the code I am using. pic1.jpg :- ! pic2. ...

``In Internet Explorer, the function to swap the image source when hovering over the parent element

I'm trying to make it so that when I hover over the parent (Li) tag with my mouse, the src attribute of the child img tag changes. This code works correctly in Chrome but not in Firefox and Internet Explorer. <li class="player"> . . //some c ...

The NextJS App directory consistently stores the retrieved data in the cache, regardless of any no-cache options that may have been configured

Despite trying various online advice, I am still facing the issue of cached fetched data. I am using a mongodb server, and even though I add data to the server, I can only see the new data on the server itself, not on the website (before the NextJS project ...

Juggling Asynchronous GET Requests in JavaScript?

Despite my efforts to find a solution, I'm struggling to come up with the right words or approach... here's the situation: In my ASP.NET MVC application, users scan inventory or package barcodes. Each scan triggers an async request, and a popup ...

Strategies for avoiding asynchronous behavior in AJAX with JQuery

My questions are best explained through code rather than words. Take a look at the snippet below and try to understand it: $('#all').on('change', function(){ //ONCHANGE RADIOBUTTON, THERE ARE #bdo, #cash also. $.ajax({ type:"GET", ...

Leveraging ES6 Classes for AngularJS 1.5 service implementation

Currently in the process of restructuring some AngularJS 1.5 service code by incorporating classes. The service definition looks like this: (() => { "use strict"; class notification { constructor($mdToast, $mdDialog, $state) { ...

Having trouble getting the Babel plugin transform-remove-console to function properly with the Vue CLI 4 and @vue/cli-plugin-babel/preset?

When you create a VueJS project using Vue CLI 4, Babel is configured with a useful preset in babel.config.js: module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ], }; I am attempting to use babel-plugin-transform-remove-conso ...

Incorporating JSON into a ColdFusion program

I have a website that showcases different views for registered and non-registered users. I am currently redesigning the product navigation to make it easier to manage by using JSON format. My website is built on Mura CMS with ColdFusion. Although what I ...

What is the best method for sending JSON data to an ASP Server through AJAX?

I'm currently working on a website built with ASP.NET that requires data retrieval from CloudKit. Utilizing CloudKit JS, I successfully retrieve a record from CloudKit and aim to send the data to the server using C# in my JavaScript code. I can conver ...

Revamping the code within the controller

I am working on an angular application that retrieves data in JSON format. Here is a sample of the data: [ { "Name": "Main", "Class": "class-o", "Base": 150, "Growth": 10 }, { "Name": "Time", "Cl ...

Unlocking the power of Angular Bootstrap UI in your controller

I have been working with the angularJS bootstrap tabset and have encountered a requirement to add a next button for customers to switch tabs. Below is an example of my code: <div ng-controller='ctr'> <tabset> <tab active=&apo ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

Sending data to a modal within a loop

I am looking to modify the functionality of my current table setup. Currently, the table is generated by iterating through all the samples passed to it via the context in views.py of my Django app, and this setup is working well. However, I want to imple ...

Stop users from repeating an action

We are encountering challenges with users repeating a specific action, even though we have measures in place to prevent it. Here is an overview of our current approach: Client side: The button becomes disabled after one click. Server side: We use a key h ...

Javascript functions triggering repeatedly

I'm working on creating a fun trivia quiz using JavaScript functions. Each question involves globally defined functions called "right" and "wrong" that are supposed to update the score accordingly. However, I've run into an issue where the quiz s ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

How can I customize the ngSrc directive in Angular to include a request header?

Is there a way to attach an authentication token to the URL request in angular js when using the ngSrc directive? If so, how can this be done? ...