Display either "All", "Multiple", or "Single" depending on the number of dropdown selections in AngularJS

I have a drop-down list of locations that appears in a pop-up, allowing users to select one, multiple, or all locations. The default label of the drop-down is "Choose Locations".

How can I address the following scenarios:

  1. If a user selects "select all" from the list, display "All" in the drop-down selection.

  2. If a user selects more than one location, display "Multiple".

  3. If a user selects only one location, display "location name".

Here is the code I am using to create the drop-down and pop-up for the list. Currently, it only displays "Choose Location(s)" regardless of the selection made by the user.

<div class="dropdown cp-dropdown">
        <div class="btn btn-default" data-toggle="dropdown">
            <!-- {{homeCtrl.newActivitySelectedLocation === '' ? 'Select Location' : homeCtrl.newActivitySelectedLocation.Name}}-->
            Choose Location(s)
      

            <span class="pull-right caret"></span>
        </div>
        <div id="location-list" class="dropdown-menu cp-checkbox-dropdown menu-container" role="menu" ng-click="$event.stopPropagation();">
            <div>
                <input type="text" ng-model="homeCtrl.newActivitySearchLocation" />
            </div>
            <div id="location-list-container">
                <div class="row" ng-if="homeCtrl.newActivityLocationList.length > 0">
                    <label class="cp-checkbox">
                        <input value="ALL" type="checkbox" id="select_all_locpop" ng-model="homeCtrl.newActivityLocationSelectAll" ng-click="homeCtrl.newActivityLocationFilter('All', homeCtrl.newActivityLocationSelectAll)" />
                        <span></span>Select All
                    </label>
                </div>
                <div id="location-list-pop">
                    <div class="row" data-ng-repeat="location in homeCtrl.newActivityLocationList | filter: {'Name':homeCtrl.newActivitySearchLocation}">
                        <label class="cp-checkbox">
                            <input value="{{location.Id}}" type="checkbox" ng-click="homeCtrl.updateActivityGrid('location-list-pop','select_all_locpop')" /><span></span>
                            {{location.Name}}
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Answer №1

Keep track of the clicks by storing them in a temporary list and change the label based on the comparison between the main list and the temporary list.

var updateLocationDisplay = function(){

  if(tempList.length === mainList.length){
    $scope.locationLabel = "All";
  }else if(tempList.length > 1){
    $scope.locationLabel = "Multiple";
  }else if(tempList.length === 1){
    $scope.locationLabel = tempList[0];
  }else{
    $scope.locationLabel = "Select a location";
  }
};

$scope.locationClick = function(name){
   var index = tempList.indexOf(name);
   if(index > 0){
     // remove it
     tempList.splice(index, 1);   
    }
   else{
    // add it
     tempList.push(name);
  }

   updateLocationDisplay();
 };

}

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

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...

Decoding the file's encoding: A beginner's guide

I need help determining the encoding of a file in order to only upload CSV files with utf-8 format. If there are any non utf-8 characters, I want to display an error message. Currently, I am utilizing Papa Parser for parsing. Is there a way to detect the ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

Error: The 'book' property is undefined and cannot be read in the BookDetails.render function

I am currently working on retrieving data from renderList and implementing it in render(). Upon using console.log this.renderList() https://i.stack.imgur.com/IwOzw.png The retrieved data is displayed above. While working on the render(), I attempted ...

Exploring the functions of `map` and `filter` in the world of

Consider this input: var m = [{ name: 'foo', routes: [{verb: 'post', path: '/foo1'}, {verb: 'get', path: '/foo2'}] }, { name: 'bar', routes: [{verb: 'put', path: ...

Are React.Fragment and DocumentFragment interchangeable in React?

React.Fragment resembles DocumentFragment. But does React.Fragment offer the same performance advantages as DocumentFragment? Put differently, do these two code snippets: // index.jsx const arr = [...Array.from({length: 10000})]; return ( <ul> ...

Utilizing Vue.js to dynamically add a class through computed properties

As a beginner in Vue.js, I want to dynamically add or remove classes based on certain conditions. Specifically, I am trying to remove the success class when the total sum exceeds 25, but for some reason the color is not changing as expected. Can anyone p ...

Tips for incorporating a download button into a video player using Plyr JS

I'm using Plyr JS and I am trying to add a download option for each video. Here is what I've done so far to make the download option work: Even though I have included: controlsList="nodownload" <video controls crossorigin playsinline contro ...

Error message "SyntaxError: Unexpected token < in JSON at position 0" encountered while using AJAX

When data is sent through an ajax request and processed, a returned array is encoded into json format. $response = array( 'data' => $leaveData, 'message' => 'Event added successfully', ...

Unwrapping Promises in Angular for Seamless Resolution

I recently started working with Angular and found myself in a large project. I encountered a simplified version of my code below: var beforeClose = function() { var closeDeferred = $q.defer(), a = $q.defer(), b = $q.defer(), c = $q.defer() ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

Establish a Connection Between Local Mongo Database and Your Application

I have successfully set up a local MongoDB connection with a React, GraphQL application. All configurations are in place and functioning properly as far as I can tell. To visually view my MongoDB databases, I have installed Compass. The content of the Ser ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Utilizing CSS Grid to arrange child elements inside their respective parent containers

I am currently working on a grid container that contains multiple divs. Each div houses different elements such as headings, paragraphs, buttons, and logos. I have utilized Flexbox to evenly distribute the logos across the container's width. However, ...

Incorporate personalized buttons into your Slick Carousel

Looking to add custom previous and next buttons to a slick carousel? I attempted using a background image on the .slick-prev and .slick-next CSS classes, as well as creating a new class following the documentation, but unfortunately, the arrows disappeared ...

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...

When a child is added to a parent in Angular UI Tree, it automatically appears in all parent nodes as well

I've been experimenting with the drag and drop feature of Angular UI Tree, and I've encountered a puzzling issue. The JSON data is fetched from my services. Upon receiving it in my controller, I need to format it correctly by adding an empty arra ...

Guide to incorporating a jade file into a node.js application after executing an Ajax request

While working on my node.js application, I encountered an issue with loading a new HTML file using Ajax on a button click. Despite everything else working perfectly, the new HTML file was not being loaded. This is how I am making the ajax call in my main. ...