Learn the process of using Angular Js to compare checkbox values with stored comma-separated values in a database

When displaying amenity checkbox options using ng-repeat of a JSON array and saving them into the database as comma-separated IDs like "1,3,7" within a single string, the challenge arises when needing to edit the amenities. This is due to retrieving the existing values from the database as "1,3,7" within a single string format. How can this string be compared to the options in the ng-repeat to display the existing values as checked?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.amenities=[{id:1,value:"Wifi"},
                  {id:2,value:"AC"},
                  {id:3,value:"Creditcard"},
                  {id:4,value:"24x7"},
                  {id:5,value:"Parking"},
                  {id:6,value:"Free delivery"},
                  {id:7,value:"No Smoking"}
                 ];

     //Assuming this is an example of existing amenities from the database
     $scope.existamenities="1,3,7";            
});

</script>

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

<div ng-repeat="amn in amenities">
  <label>{{amn.value}}
<input type="checkbox" name="amenities" ng-value="amn.id">
</label>
</div>

</div>

</html>

Answer №1

To ensure that the checkboxes are properly checked, you should set the ng-model to true or false based on the values. You can achieve this by creating a new array and updating it accordingly.

One approach is to add new properties to the existing array that will store true/false values, or create a new array based on the original one. Then, you can change default false values to true if their corresponding ID is present in the list obtained by splitting the string.

Below is a simple demonstration:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.amenities = [
    {id:1,value:"Wifi"},
    {id:2,value:"AC"},
    {id:3,value:"Creditcard"},
    {id:4,value:"24x7"},
    {id:5,value:"Parking"},
    {id:6,value:"Free delivery"},
    {id:7,value:"No Smoking"}
  ];

  //Assuming this is the existing list of amenities from the database
  $scope.existamenities = "1,3,7";

  var a = $scope.existamenities.split(",").map(x => Number(x))
  var b = $scope.amenities.map((x) => {
    return {
      "id": x.id,
      "val": false
    }
  })
  for (var i = 0; i < b.length; i++) {
    for (var j = 0; j < a.length; j++) {
      if (b[i].id == a[j]) {
        b[i].val = true
      }
    }
  }
  $scope.model = b;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  <div ng-repeat="amn in amenities">
    <label>{{amn.value}}
<input type="checkbox"  name="amenities"  ng-model="model[$index].val" ng-value="amn.id">
</label>
  </div>

Answer №2

To effectively manage the checkboxes and determine which ones are checked, you must utilize the ng-model directive for each checkbox. This allows you to track their status and identify the checked ones during form submission.

To implement this, follow these steps:

  • Include a checked property in the Amenities objects
  • Bind the ng-model of the checkboxes in the ng-repeat to the corresponding checked property

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.amenities=[{id:1,value:"Wifi", checked: false},
                  {id:2,value:"AC", checked: false},
                  {id:3,value:"Creditcard", checked: false},
                  {id:4,value:"24x7", checked: false},
                  {id:5,value:"Parking", checked: false},
                  {id:6,value:"Free delivery", checked: false},
                  {id:7,value:"No Smoking", checked: false}
                 ];

     // Assume these are existing amenities fetched from the database
     $scope.existamenities="1,3,7";            

     var arrayOfExistingAmenities = $scope.existamenities.split(",");
     arrayOfExistingAmenities.forEach(function(existingAmenity) {
        $scope.amenities.forEach(function(amenity) {
            if (amenity.id == parseInt(existingAmenity)) {
                amenity.checked = true;
            }
        });
     });

});

</script>

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

<div ng-repeat="amn in amenities">
  <label>{{amn.value}}
<input type="checkbox" name="amenities" ng-model="amn.checked" ng-value="amn.id">
</label>
</div>

</div>

</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

Issue with remove functionality in Vue js implementation causing erratic behavior in my script

Within my Vue.js code, I have a functionality that displays categories from an API. When a category is clicked, it is added to the AddCategory array and then posted to the API. I have also implemented a button called RemoveAll which successfully empties th ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

Learn the process of eliminating special characters from input or textarea fields with AngularJs!

My attempts to integrate an AngularJS directive to remove special characters from input and textarea fields have been unsuccessful. Despite no errors being reported in the console, I am facing issues with the character count tooltip not displaying numbers ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...

Explore innovative circular navigation with the wheelnav.js library - where SVG elements can dynamically change position but keep

I recently started exploring wheelnav.js for creating a unique navigation system. The Spreader feature caught my attention, particularly the 2nd example. However, when I implemented it, the text did not rotate as expected. I followed the code example pre ...

What is the best way to display a div based on a keyword match?

If the keyword search results in a match, I can display the corresponding input text and its related category div. Now, I am attempting to also search through category names. If the searched keyword matches a category name, that specific div should be visi ...

What is the best way to create a flexible Ul-LI menu?

Is it possible to create a flexible menu where clicking on an item does not cover other items in the menu? #demo { margin: 30px 0 50px 0; font-family: sans-serif; } #demo .wrapper { display: inline-block; width: 180px; height: 20px; position ...

Instructions on inserting an IFRAME using JavaScript into dynamically loaded content via AJAX

How can I dynamically add an IFRAME using JavaScript to content that is refreshed via AJAX? Consider the following example: $('#bar').delegate('.scroll-content-item span a', 'click', function() { var object_id = $(this).p ...

The issue of variable being undefined in JSON for JavaScript and Python

Consider a scenario where you have the following JSON object (remove the semicolon for python): values = { a: 1, b: { c: 2, d: { e: 3 } }, f: 4, g: 5 }; When attempting to print values in JavaScript, it will work pr ...

What's the Hold-Up with IntersectionObserver in Brackets?

As a novice in the world of web development, I have been utilizing Brackets as my main tool. Recently, I've encountered a few hurdles specifically related to javascript. One issue I'm facing is trying to implement lazy loading on a div containing ...

The evaluate function is not functioning as expected

Code: console.log(propertyName); console.log(eval(this.state.propertyName)) console.log(this.state.DriverFirstName); Output: DriverFirstName undefined fsdfds I am attempting to access a variable defined by a string value (propertyNa ...

A guide on instantly updating displayed flat/section list elements in React Native

I am in the process of creating a screen called ContactListScreen. The direct child of ContactListScreen is ContactItems, which is a sectionList responsible for rendering each individual ContactItem. However, I have encountered a problem where my ContactIt ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Revamp your array elements with MongoDB - Substring replacement

Having some difficulty replacing a substring within various documents. Below is an example of one such document: { "images" : [ { "url" : "https://example/1234" }, { "url" : "https://example/afaef" }, { "url" : ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

What is the best way to dynamically write a knockout data binding event using jQuery?

let $button = $('<input/>').attr({ type: 'button', value: data.styleData, id: buttonId, data - bind: event: { click: $parent.submitPopUp } }); An error is being displayed. ...

Encountering a problem during the installation of the udev module in a Node.js

When I run the command below: npm install udev I encounter the following error message: npm WARN enoent ENOENT: no such file or directory, open '/home/mitesh/package.json' npm WARN mitesh No description npm WARN mitesh No repository field. ...

Issues with Three.js materials not rendering properly when loading .obj and .mtl files

I recently downloaded a free 3D model and I'm attempting to view it using three.js. Although the model is loading correctly, there seems to be an issue with the materials not loading properly. Strangely enough, only the wine bottles behind the bar are ...

Is it possible to retrieve resolved parameters from a template-rendering function?

I'm facing a scenario where I have a state setup like this .state('dropdown', { url: '/dropdown', views: { "@":{ template: ...