Guidelines for choosing AngularJS checkboxes to exclusively choose distinct matching items

Need help with selecting common items using Angular checkboxes.

Below is the mock UI-Table:

  Order Id  | Delivery Mode  | Select
      1     | Speed          | ::checkbox::
      2     | Normal         | ::checkbox::
      3     | Contractor     | ::checkbox:: 
      4     | Contractor     | ::checkbox::
      5     | Normal         | ::checkbox::
      6     | Speed          | ::checkbox::
      7     | Speed          | ::checkbox::
                       :::Create Order button:::

Conditions:

  • All checkboxes are enabled by default and can only select orders of the same delivery mode.
  • If mixed delivery modes are selected, display an error message (like an alert).

Orders list used for populating the table:

var orders = [
{
  orderId: 1,
  deliveryMode: 'Speed'
},
{
  orderId: 2,
  deliveryMode: 'Normal'
},
...
...
];

Controller logic:

$scope.createOrder = function(order) {
 if(order.selected){
  $scope.collectOrders.push(order.deliveryMode);
 }else{
  _.remove($scope.collectOrders, function(order){
    return order === order.deliveryMode;
  });
 }

  if (_.uniq($scope.collectOrders).length > 1){
    alert('Mixed Delivery mode selected');
  }

};

Looking for a more efficient solution to only allow selection of common delivery mode. Any suggestions?

Answer №1

Utilize this code snippet to choose items with a similar delivery mode.

HTML Markup :

<tr ng-repeat="row in orders track by $index">
    <td name="checkbox"><input type="checkbox" ng-model="row.checked" ng-style="row.checkboxStyle" ng-click="setSelectedRow(row)" /></td>
</tr>

JavaScript Function :

$scope.mySelections = [];
$scope.setSelectedRow = function(row) {
    if ($scope.mySelections.length === 0) {
        $scope.mySelections.unshift(row);
        return;
    }
    var index = $scope.mySelections.indexOf(row);
    if (row.checked) {
        if ($scope.mySelections.length > 0) {
            if (row.deliveryMode === $scope.mySelections[index - 1].deliveryMode) {
                $scope.mySelections.unshift(row);
            } else {
                alert("Mixed Mode Selected");
            }

        } else {
            $scope.mySelections.unshift(row);
        }


    } else {
        $scope.mySelections.splice($scope.mySelections.indexOf(row), 1);
    }
};

Answer №2

To ensure that the checkbox remains disabled when a different type is selected, you can utilize ng-disable in your code.

<md-checkbox ng-repeat="item in items" ng-disabled="selectedItem.type !== item.type" ng-change= "updateItem(item)">

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

It is necessary for ReactJS eslint rules to employ destructuring when assigning state

class MyDrawer extends Component { const modalOpen = this.state; // Initialize state in the constructor render() { return ( <div> <Drawer modal open={this.state.modalOpen} // <-- this line show error ...

How can we know when a JavaScript ES6 arrow function comes to a close?

One thing I've been pondering is how an arrow function terminates when it lacks brackets. I encountered this issue when working with ReactJS, where I had a function followed by the start of a class declaration. Here's the snippet: const Search = ...

Applying a consistent script with varying inputs on the same HTML page

Is it possible to create a JavaScript code that can be used across different sections of an HTML document? The goal is for the script to fetch data such as title, runtime, and plot from a specific URL request and insert this information into the appropriat ...

Trying to assign a value to the property 'male' of an undefined object - error encountered while setting object value from an array

Why is it that when I add one more testObject, the code doesn't work anymore? The line of code where only one testObject is used works fine (testObject[Object.values(testObject)[0]]=5), but adding another testObject causes issues. const testObject ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

Stopping a NodeJS script execution: Tips and Tricks

While working on my NodeJS application, I've noticed that occasionally my CPU usage spikes to 100%, but there is no memory variation. This causes my Event Loop to become blocked by the operation. I recalled how browsers handle problematic scripts by ...

Experiencing difficulties with a cross-domain jQuery/AJAX service request

After extensively researching various threads both on this platform and elsewhere, I have been trying to successfully execute a cross-domain AJAX call. The scenario involves a Restful WCF service that simply returns a boolean value. The service is configur ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

I'm experiencing some issues with the JavaScript setTimeout function - can anyone help troubleshoot

in my quest to find a way to hide the notificationBar without the use of a button and using XX.hide() oncomplete, I stumbled upon a javascript snippet <script type="text/javascript> jQuery(function() { bar.show(); setT ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

React is generating an error when attempting to use hooks without the appropriate class name prefix

I'm encountering an error when I use hooks without a class name prefix. Can someone help me troubleshoot this issue? import React, {Fragment,useState} from 'react'; function App (props) { const [x,updateX] = useState(1) /* throwing error ...

React component unmounts but listener remains attached

After developing a SPA using react.js, I have incorporated react-router-dom, react-redux, and various other modules. The routes defined in my application: const allRoutes = [ { path: "/Intro", name: "Intro", component: Intro }, ...

Guide on creating and synchronizing an XML/JSON file that stores beat information (BPM) for audio using JavaScript

Looking to sync Javascript events with the BPM of music for a game similar to "Guitar Hero." We start with: In order to create a track file based on beat detection (with each BPM saved like sheet music), how can it be generated beforehand rather than in ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

Would combining node.js with express for the back-end and emberjs for the client side be a suitable choice for my project?

As a seasoned web developer, I have limited experience with nodejs and have yet to dive into the world of emberjs (although I have worked extensively with backbone). I am embarking on a new project to create a web-based writing application focused on lite ...

Ensure that jquery.load is executed before the HTML content is loaded

Recently, I encountered a situation where I had a bootstrap navbar stored in a separate file, specifically named navbar.html. I utilized Jquery.load() to load this navbar into my HTML page. At the bottom of my HTML page, I included the following code: &l ...

Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template: <a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a> <button>Close tab</button> The c ...

react validation for dropdown, react-datepicker, and hour input at intermittent intervals

I have integrated the following packages into my project :- react-datepicker library for selecting from time and to time date validation with date-fns, moment.js, additional validations using jQuery and lodash libraries/packages If you want to view my pr ...

Unable to alter state from the onClick event of a dialog button

In the process of developing a Next.js app, I encountered an interesting challenge within one of the components involving a DropdownMenu that triggers a DialogAlert (both powered by Shadcn components). The issue arises when attempting to manage the dialog& ...