How can I make a checkbox checked in AngularJS?

Hello, I am currently working on a web application using AngularJS. Within this application, I have a form where I am populating values into a multi-select dropdown.

  <li ng-repeat="p in locations">
  <input type="checkbox" ng-checked="master" ng-model="isTrue" ng-change="getIndex(p.Location,isTrue )" ng-name="location" required/>
  <span>{{p.Location}}</span>
  </li>

The values are being bound from an array called 'locations', which looks like:

0:  id: 1  Location:"ABC"
1:  id: 2  Location:"DEF"
2:  id: 3  Location:"IJK"

My current goal is to pre-check specific values within the multi-select dropdown. For example, if I have a variable var locations="ABC,DEF", I want only those values to be checked initially. If you have any insights on how this can be achieved, your assistance would be greatly appreciated. Thank you!

Answer №1

Essentially, if we have a string input with the selected locations (e.g.) var destinations = 'ABC,DEF';, we can divide this string by the , character to create an array of locations to compare:

var app = angular.module('myApp', []);

app.controller("locationsController", ["$scope",
    function ($scope) {
        // variables
        var locations = 'ABC,DEF';
    
        // functions
        function initialize() {
            var localities = locations.split(',');
        
            angular.forEach($scope.locations, function (item) {
                if (locations.indexOf(item.Location) > -1) {
                    item.checked = true;
                }
            });
        }
    
        // $scope
        $scope.locations = [
            { id: 1, Location: "ABC" }, 
            { id: 1, Location: "DEF" }, 
            { id: 1, Location: "IJK" }
        ];
        
        // initialization
        initialize();
    }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
   <div ng-controller="locationsController">
      <li ng-repeat="p in locations">
         <input ng-checked="p.checked" type="checkbox" ng-model="p.checked" required/>
         <span>{{ p.Location }}</span>
      </li>
   </div>
</div>

Answer №2

Here is a suggestion to improve your code. Assign a separate model for each checkbox.

var app = angular.module('myApp', []);

app.controller("Controller", ["$scope",
  function($scope) {
    $scope.locations = [{
      "id": 1,
      Location: "ABC"
    }, {
      "id": 1,
      Location: "DEF"
    }, {
      "id": 1,
      Location: "IJK"
    }]

    var checked = ['ABC','DEF'];
    function init() {
      angular.forEach($scope.locations,function(location){
        if(checked.indexOf(location.Location) != -1){
          location.checked = true;
         }
      })
    }
    init();

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller">
    <li ng-repeat="p in locations">
      <input type="checkbox" ng-model="p.checked" name="location" required/>
      <span>{{p.Location}}</span>
    </li>
  </div>
</div>

Answer №3

Here is a sample code that should be functional:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope,$filter) {

  $scope.selectedValue = 'ABC,IJK';
  $scope.selectedValue = $scope.selectedValue.split(',');
 
  $scope.options = [{
    id: 0,
    name: 'ABC'
  }, {
    id: 1,
    name: 'DEF'
  }, {
    id: 2,
    name: 'IJK'
  }];
  $scope.selected = [];
  angular.forEach($scope.selectedValue,function(val,key){
  var r = $filter('filter')( $scope.options, {name: val})[0].id;  
  if(r != undefined){
   $scope.selected[r]=true;
  }else{
   $scope.selected[r]=false;
   }
  
 
  });
  

});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

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

    <li ng-repeat="p in options">
      <input type="checkbox" ng-model="selected[p.id]" ng-change="getIndex(p.Location,isTrue )" />
      <span>{{p.name}}</span>
    </li>
    Selected : {{selected}}
  </div>

Answer №4

Give this a try:

<ul ng-repeat="place in areas">
  <input type="checkbox" ng-checked="place.Area == 'XYZ' || place.Area == 'LMN'? true : false" ng-model="place.master" ng-change="findIndex(place.Area, checkStatus )" ng-name="area" required/>
  <span>{{place.Area}}</span>
</ul>

Answer №5

Include an additional field checked:"true" in your locations array like so

var app = angular.module('myApp', []);

app.controller("Controller", ["$scope",
  function($scope) {
    $scope.locations = [{id:1,Location:"ABC",checked:"false"},{id:1,Location:"DEF",checked:"true"},{id:1,Location:"IJK",checked:"true"}]

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller">
    <li ng-repeat="p in locations">
      <input ng-checked="{{p.checked}}" type="checkbox" ng-model="p.id"  name="location" required/>
      <span>{{p.Location}}</span>
    </li>
  </div>
</div>

Answer №6

Consider implementing this method to achieve the desired result. You will need to assign a unique ngModel for each checkbox by placing them inside the location object itself.

Sample HTML:

 <li ng-repeat="p in locations">
     <input type="checkbox" ng-checked="master" ng-model="p.isTrue" ng-change="getIndex(p.Location, p.isTrue)" ng-name="location" required/>
     <span>{{p.Location}}</span>
 </li>

In JavaScript:

$scope.locations = [
    {id: 1, Location:"ABC"},
    {id: 2, Location:"DEF"},
    {id: 3, Location:"GHI"}
];
var selectedLocations = "ABC,DEF";
selectedLocations = locations.split(",");
angular.forEach($scope.locations, function(loc){
    loc.isTrue = selectedLocations.indexOf(loc.Location) > -1;
});

Answer №7

Add a new element to your array and assign a boolean value of true or false to it.

0: id: 1 Location:"ABC" flag: true
1: id: 2 Location:"DEF" flag: false

<li ng-repeat="p in locations">
    <input type="checkbox" ng-checked="p.flag" ng-model="isTrue" ng-
    change="getIndex(p.Location, isTrue)" ng-name="location" required/>
    <span>{{p.Location}}</span>
</li> 

Utilize that flag to toggle the state of your checkbox.

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

In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview $scope.year = [ {"month":"mar", "val":"23"}, {"month":"feb", ...

What is the best way to establish a two-way connection between two arrays?

Within my application, there is an ItemsService responsible for fetching Items from the server and storing them as JSON objects in its cache. These Items may be displayed in various formats such as tables, graphs, or charts. For instance, when setting up ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

Adding Labels to Doughnut Charts in React using Chart.js 2.0

Currently, I'm exploring the world of data visualizations using react, react-chartjs-2, and chart.js version 2.2.1. While searching for a solution to my inquiry, I came across a potentially relevant answer on this link (specifically check out the upda ...

Managing "unprocessed information" in a Node.js environment and transferring the information through a Node Express endpoint

Currently, I am in the process of making an API call to retrieve a file using axios: async function fetchData() { const configuration = {}; // { responseType: 'stream'}; const { response } = await axios.get(URL, configuration); c ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

How can we use jQuery to extract an HTML element's external stylesheet and add it to its "style" attribute?

My goal is to extract all CSS references from an external stylesheet, such as <link rel="stylesheet" href="css/General.css">, and add them to the existing styling of each HTML element on my page (converting all CSS to inline). The reason for this re ...

The issue with ng-if not functioning within ng-repeat is that the ng-if directive

My issue is with using ng-if inside an ng-repeat in AngularJS. Despite updating to the latest version on 09/27/2014, I am still unable to make it work properly. The code functions perfectly outside of ng-repeat, and also works fine inside ng-repeat when us ...

What is the proper way to utilize the name, ref, and defaultValue parameters in a select-option element in React Meteor?

I recently developed a Meteor project using ReactJS. I have a Create/Edit page where I use the same input field for various form elements. Here is an example of code snippet that I currently have: <FormGroup> <ControlLabel>Province</Control ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Passing a JSON object as a parameter in a dynamically created element's click event using JavaScript/AngularJS

How to pass a JSON object as a parameter in the click event of a dynamically created element using JavaScript and AngularJS? var _dataObj = "{"sor_SourcingAgentId":1,"sor_Name":"xx"}" var _dynHtml= '<input type="button" ng-click="fnSelectcustom ...

Express-Session Object Method

I am currently facing an issue with linking an object to an Express session. Below is the code I am using: var express = require('express'); var session = require('express-session'); // Defining an object named "engine" which simulate ...

Is it possible to implement hierarchical validation within reactflow nodes?

I am currently utilizing reactflow to establish a network of sequences, each possessing their own unique "levels." My primary objective is to restrict connections between sequences based on their respective levels. For instance, a level 5 sequence should ...

Dynamic Code for Removing List Items Based on Date

I need assistance in resolving an issue with my company's website design and function. Specifically, I am working on a page that displays a list of events where employees will be present throughout the year. Here is an example: <div class="contai ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

Unable to retrieve information obtained from MongoDB

After successfully retrieving all data from the "topics" collection using find() with cursor and foreach, I am encountering an issue. When I attempt to assign the fetched information to a variable named "data" and send it back to the page, it consistently ...

Managed the double-click event to select Snap.svg text

I am currently utilizing the snapsvg library for a project where I am implementing the dblclick event to trigger a browser window alert. However, when clicking on the svg canvas, not only does the alert pop up but some text on the canvas also gets selected ...