Monitoring changes to an array of objects in AngularJS within a Select tag using the ng-repeat directive

My goal is to monitor select tags using ng-repeat and disable the save button. My current setup includes:

  • Initially, I will have three select boxes with values. The user must select at least one value from these boxes to enable the Save button.

    • The user can also add more select boxes as needed.

How can I watch all five select boxes and enable/disable the Save button based on whether any of them are selected?

Here is a fiddle link that showcases a similar situation:

<a href="http://jsfiddle.net/37Lrvc8n" rel="nofollow">Js fiddle</a>
Any assistance would be greatly appreciated!

Answer №1

To ensure that all selects are filled out, you can enclose them inside a form and mark them as required. Then, in the button, you can check the validity using the ng-disabled tag if the form is $invalid.

For example:

<ng-form name="selectForm">
  <select class="form-control" ng-model="item.name" name="select" ng-required="true">
    <option>Select a campus</option>
    <option>Campus 1</option>
    <option>Campus 2</option>
    <option>Campus 3</option>        
  </select>
  <button type="submit" ng-disabled="selectForm.$invalid">Save</button>
</ng-form>

Answer №2

Utilizing the same object as a model for all ng-select elements is a great technique:

$scope.selectedValues = {};

Each select box within an ng-repeat loop can then use a different object property as its model:

<select class="form-control" ng-model="selectedValues['campus_' + $index]">
    <option>Select a campus</option>
    <option>Campus 1</option>
    <option>Campus 2</option>
    <option>Campus 3</option>        
</select>

To verify if all values are populated, observe changes in the selectedValues object with the last parameter set to true:

$scope.$watch('selectedValues', function(newValue, oldValue) {
    // Check whether all values in $scope.selectedValues are filled
    var allFilled = true;
    angular.forEach($scope.selectedValues, function(value, key) {
        if (!value) {
            allFilled = false;
        }
    });

    if (allFilled) {
        // enable button
    } else {
        // disable button
    }
}, true);

The inclusion of true as the last parameter is crucial as it instructs Angular to compare all values in the object. Refer to https://docs.angularjs.org/api/ng/type/$rootScope.Scope for more information.

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

The Effective Implementation of Ui-Select within UI-Grid

After receiving a positive response to my initial inquiry on this platform, I am excited to present another question. I have successfully implemented Brian Hamm's method for incorporating a ui-select in ui-grid. However, I seem to be facing an issue w ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

What is the process for sending an image as input to a Django view using an Angular frontend?

I currently have a django web api with an angular frontend that allows users to upload and view images. My goal now is to expand this functionality: when the user clicks the "segment" button (see image), it should send the corresponding image to my python ...

I often find myself feeling unsure when I incorporate conditional logic in JSX within Next.js

Hello, I am currently using Next.js and encountering an issue with using if/else in JSX. When I use if conditions, the classes of elements do not load correctly. Here is my code: <Nav> { login ? ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...

Exploring the combination of Express router, Auth0, and plain Javascript: A guide to implementing post-login authentication on a router

After creating a front end with vite using vanilla javascript and setting up a backend with node.js express routes, I successfully integrated swagger for testing purposes. I have managed to enable functionalities such as logging in, logging out, and securi ...

What are the reasons behind the pagination with numbers not functioning properly in Vue?

I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the paginat ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

Issue with EJS template displaying no information

I am encountering an issue with ejs templates. While I have successfully used it in a previous project, in my current one, it's not working as intended. Instead of rendering the cards with the passed data, all I see is a blank page. Here is my code fo ...

Having issues with the link page in react-router-dom?

Currently, I am utilizing the react-router-dom library to manage routers. However, I have encountered an issue where linking to another page does not change the page, but instead adds the new page right after the previous one as shown in the image below. W ...

Utilize Laravel to trigger a route action based on a dropdown selection change, generating a unique URL

In my code, I have a dropdown select containing the list of the next 12 months: <select name="month" id="specificMonth"> @foreach(Carbon\CarbonPeriod::create(now()->startOfMonth(), '1 month', now()->addMon ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

Having trouble uploading images using ReactJS on the web platform

I am currently in the process of developing a portfolio website using react js, but I'm experiencing an issue where the image I intended to display is not showing up on the live site. Despite thoroughly checking my code, I can't seem to identify ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Javascript functions function properly only if they contain the 'alert()' command

My aim is to utilize Ajax (Javascript + php) for checking user name availability when a user moves focus to another form field. The strange part is that my functions only work when I include some alert(), without them, the functions fail to operate. Anoth ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Toggle class on child element when parent is clicked

I am currently working on a functional React component that looks like this: const RefreshButton = () => ( <IconButton> <RefreshIcon /> </IconButton> ) My goal is to dynamically assign a class attribute ...

What are the drawbacks of automating the process of generating charts to track time spent on webpages?

!RESOLVED! I am looking to automatically generate charts based on users and their time spent on different pages of a website. I have a file named "log.xml" where I store user information (customers), visited pages, dates, and the time they spent; once I ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...