AngularJS check box functionality

I am looking for a way to display the values of an array based on checkbox selection. Here is the code snippet:

Javascript:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= [{name:"John",selected:"false"},{name:"Anil",selected:"false"},{name:"Kumar",selected:"false"}];
    $scope.lastName= "Doe";
    $scope.name1=[],
    $scope.addname=function(){
    angular.forEach($scope.firstName, function(name,selected){
  if(selected=="true") {
  alert(name);
    $scope.name1.push(name)
  }
});
 }
 });

html:

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

<tr ng-repeat="first in firstName">
<td><input type="Checkbox" ng-model="first.selected">{{first.name}}</td>

</tr>
<tr><td><input type="Button" ng-click="addname()" value="Submit" ng-model="lastName"></td></tr>

<tr ng-repeat="nam in name1">{{nam}}</tr>
</table>
</div>

Answer №1

  • Ensure the selected value remains as type Boolean instead of String
  • When using forEach, remember that the first argument is an Object; access the associated model by using name.selected
  • Create and initialize the array name1 within the ng-click handler

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstName = [{
    name: "John",
    selected: false
  }, {
    name: "Anil",
    selected: false
  }, {
    name: "Kumar",
    selected: false
  }];
  $scope.lastName = "Doe";
  $scope.addname = function() {
    $scope.name1 = [];
    angular.forEach($scope.firstName, function(name, selected) {
      if (name.selected) {
        $scope.name1.push(name)
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <table>
    <tr ng-repeat="first in firstName">
      <td>
        <input type="Checkbox" ng-model="first.selected">{{first.name}}</td>
    </tr>
    <tr>
      <td>
        <input type="Button" ng-click="addname()" value="Submit" ng-model="lastName">
      </td>
    </tr>
    <tr ng-repeat="nam in name1">{{nam}}</tr>
  </table>
  {{name1}}
</div>

Answer №2

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= [{name:"John",selected:false},{name:"Anil",selected:false},{name:"Kumar",selected:false}];
    $scope.lastName= "Doe";
    $scope.name1=[];
    $scope.addname=function(){
    angular.forEach($scope.firstName, function(name){
      if(name.selected === "true") {
        $scope.name1.push(name);
      }
});
 }
 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table >

<tr ng-repeat="first in firstName">
<td><input type="Checkbox" ng-model="first.selected"  ng-true-value="true" >{{first.name}}</td>

</tr>
<tr><td><input type="Button" ng-click="addname()" value="Submit" ng-model="lastName"></td></tr>
<tr ng-repeat="nam in name1"><td>{{nam}}</td></tr>

</table>
</div>

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

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

Steps to implement a fixed toolbar in Chrome while ensuring optimal functionality for all other fixed elements

Currently in the process of developing a Chrome extension, I'm interested in implementing a 60px height toolbar that remains visible at the top of all pages. I've researched various tutorials and articles on using CSS translateX, but encountered ...

What are some methods to alert my JS client without constant polling?

Situation: In my web application, I trigger a lengthy operation using JavaScript that runs on the .NET2.0 backend. The call returns quickly with an operation ID while the operation continues in the background. These operations don't require much CPU p ...

Issue with JavaScript HTML Section Changer not functioning properly

I need to implement a button that switches between two pages when pressed. Although the code seems simple, I am struggling to make it work. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

JS stop the timer from the previous function call before starting a new function call

Within my React app, I have implemented a slider component from Material UI. Each time the slider is moved, its onChange event triggers a function to update the state. However, I have noticed that the component rerenders for every step of the slider moveme ...

Unable to adjust price slider on mobile device, bars are not sliding

I have been utilizing the jQuery slider from lugolabs.com for my website, and while it works flawlessly on desktop, it seems to have issues when viewed on mobile devices. You can check out the slider at this link: The library used for this slider is jQue ...

Unexpected Timed Out error from Socket.IO adapter when MongoDB connection is lost

I have been experimenting with capturing the disconnection event in mongodb. Everything is working smoothly with this setup: simple.js 'use strict'; var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:2701 ...

Exploring ways to eliminate an item from a dropdown list within an array using Vue JS

I am currently utilizing an array named 'itemsCart' in my data() and presenting this array within a dropdown list. I have implemented a button to remove items from the array, but I am unsure of how to proceed. Below is my code snippet: <Breeze ...

step-by-step guide for resolving issues with downloading files in node.js

I've been attempting to download files from my server using node.js with the res.download function from Express, but I keep getting an undefined error. The folder path is D:\program\web\java_script\Node\my_project\ketabk& ...

Loading Data into Gridview with Ajax

I am facing a challenge with two gridviews. When a row in one grid is clicked, I need to populate the other gridview. To achieve this, I have implemented an onClientClick JavaScript function that triggers an AJAX call to fetch data from a datatable for pop ...

What causes a "UnhandledPromiseRejectionWarning" while using Puppeteer?

What causes the following warnings to appear, and how can I resolve them? Warnings: (node:26771) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Protocol error (Runtime.callFunctionOn): Target closed. (node:26771) ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Steps to automatically fill out a form with the last ID retrieved from MySQL upon submission

I am currently developing an order form that will populate data in two MySQL tables: "order" and "order_details." Both tables contain the order_number column. To simplify this process, I have created a third table named "order_num" that stores order number ...

Converting "require" to ES6 "import/export" syntax for Node modules

Looking to utilize the pokedex-promise for a pokemonapi, however, the documentation only provides examples on how to require it in vanilla JavaScript: npm install pokedex-promise-v2 --save var Pokedex = require('pokedex-promise-v2'); var P = new ...

Alert Div from Bootstrap fails to appear during the second ajax request if the first ajax request is canceled

I've implemented a dismissible alert in my HTML file that starts off hidden. Here's the code snippet: <div class="alert alert-dismissible" role="alert" id="msgdiv" style="margin-bottom:5px;display: none;"> <button type="button" clas ...

Accessing Cognito using ReactJS and fetching data with specific parameters

I'm currently attempting to retrieve the email of the user who is logged in and use it within my fetch() call. I have successfully obtained the email using getfirstapi() and used it in my form, but I am encountering issues when trying to pass it into ...

Using Underscore.js to Group JSON Data in jQuery

I am looking to format my JSON data in order to create a chart for my daily reporting templates. The chart should display the number of Approved, Rejected, and Pending items on a daily basis. The current JSON data I have is as follows: json_data = '[ ...

Using the React useEffect hook to manage state in React applications

When a button is clicked in my app, the state of endpoint changes and data is fetched from my API. While waiting for the data to be retrieved, I wanted to display a loading icon which was quite challenging to implement but after much testing, I finally got ...

What is the best way to save a hash in a form input field?

If I have a hash and want to pass it as a value with val() $("#form_attribute").val( hash ) Instead of storing it as a string "[Object, object]", how can I keep it as a hash and allow the form to send this hash to my server? ...

Is there a way to modify an element in an array in AngularJS without using splice?

I encountered a situation similar to the one described in this post here, where I not only want to retrieve an element but also change its name value. I came across a method that involves using splice: dataList.splice(index, 1); dataList.splice(index, 0, ...