Tips for Checkbox Group validation in Angular JS and Angular Material upon clicking

I have encountered an issue while using Angular Material for simple validation with checkboxes.

The Challenge :

Requirement: At least one checkbox must be checked.

1- When I click a checkbox and then click again, the "required message" does not appear.

2- After clicking a checkbox, pressing the "Tab key" to navigate through each checkbox results in the "Required" message appearing only when reaching the last checkbox and pressing Tab again.

I am seeking a solution where condition number 1 also triggers as expected. Additionally, I do not want the "required" message to display upon application loading. Here is my example : https://codepen.io/anon/pen/zrjjyL

Your assistance would be greatly appreciated. Thank you!

Code :

HTML:

 <form name="myForm" ng-app="myApp" ng-controller="myController"  
 class="container-fluid" ng-submit="submit()">

<div class="row">
<div class="col-xs-8">
   <md-input-container md-no-float>
           <label>Name *</label>
           <input required="" name="nombre" ng-model="model.nombre">
           <div ng-messages="myForm.nombre.$error" ng-
show="myForm.nombre.$touched || myForm.$submitted">
              <div ng-message="required">Required.</div>
           </div>
        </md-input-container>
  <md-input-container md-no-float>
           <label>Search Options *</label>
           <input type="text" id="query" ng-model="query"/>
        </md-input-container>
   <md-input-container md-no-float>


        <md-list-item ng-repeat="item in items | filter:query">
            <p style ="font-size: 1.3rem;font-family: Roboto,'Helvetica 
Neue',sans-serif"> {{ item.title }} </p>

               <md-checkbox name ="permiso" ng-
model="model.opciones[item.id]['checked']" ng-required="!isChecked" ></md-
checkbox>
        </md-list-item>

 <div ng-messages="myForm.permiso.$error" ng-show=" myForm.permiso.$touched  
 || myForm.$submitted">
             <div ng-message="required">Required.</div>

        </md-input-container>


</div> </div>

JS:

var app = angular.module('myApp', ['ngAnimate', 'ngAria', 'ngMaterial',  
'ngMessages'])
.controller('myController', function($scope) {

    $scope.items = [{
        id: 1,
        title: 'Item A'
    }, {
        id: 2,
        title: 'Item A'
    }, {
        id: 3,
        title: 'Item C'
    }];;

    $scope.model = {}
    $scope.model.opciones = {};
    $scope.isChecked = false;
    $scope.$watch('model.opciones', function(selected) {
        $scope.isChecked = false;
        angular.forEach(selected, function(selectedItem) {
            if (selectedItem.checked) $scope.isChecked = true;
        });
    }, true);
});

Answer №1

To determine if the form has been altered, use formName.$dirty. This way, you can limit displaying errors only when the form has indeed been modified.

<div ng-message="required" ng-if="myForm.$dirty">Required.</div>

Answer №2

As you iterate over your list of items, the myForm.permiso value is constantly being updated with each new item, resulting in only the last change being registered when tabbing through them.

To resolve this issue, consider removing the name attribute from the checkboxes and implementing an ng-change handler instead of using $watch. Additionally, you can include a hidden checkbox for the permiso model that gets updated whenever there is a change.

For more information, check out this CodePen example: https://codepen.io/kuhnroyal/pen/LGrzGv

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

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

Step-by-step guide on triggering a parent component event from a child component in Vue3 programmatically

I am currently working on a Vue 3 project where I utilize a component named revogrid to build a dashboard. This particular component requires another component to render a cell as a parameter. My goal is to create an event within the child component that c ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

Inquiring about the best method to determine the intersection point between two lines in Draw i.o

Can someone please explain how to find the coordinate point where two lines intersect in draw i.o? I am looking for a Javascript function to solve this issue and get the coordinate of the point only. For example: ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

Function call fails when parameters are passed

I've been grappling with this conundrum for a few weeks now, on and off. Perhaps someone else will spot the glaringly obvious thing that I seem to be overlooking. At the present moment, my primary goal is to simply confirm that the function is operat ...

Resetting an Angular Material select component

I've encountered an issue with Angular Material. Currently, I have a form with two select elements. The problem arises when I choose a value in one of the selects, it resets and loses its value. Could this be a bug? Or am I possibly making a mistake ...

Dynamically loading controllers and templates in AngularJS based on routes

Seeking a solution for dynamically loading both a template and controller based on the route in Angular 1.6 from the local directory structure. resolve with a promise statement.</p> Assistance is requested in developing a resolve using a simple pro ...

Determine the Total of a Column in jqgrid

Hey there, I'm looking for a way to calculate the total sum of the "montant" column in my jqgrid and then display it below the grid as "Total: *total amount*". Here is the code for my grid: <sjg:grid id="gridtable" caption="Quittance Payé ...

Show the ajax appended html only after reaching a specific threshold

I am currently utilizing AJAX to fetch additional results from my database. Below is the basic script I am using: $('#loadmorebuilds-div').click(function() { $.ajax({ url: 'includes/loadmorebuilds.php?type=' + type + &ap ...

How can I position images in the center evenly?

I am currently working on implementing a 3D image carousel. It seems to work fine with an odd number of images, but when I add an even number of images and the positions change, the alignment gets offset to the left instead of center. Here is the link to ...

Enhancing menu item visibility with Typescript and Vue.js 3: A step-by-step guide

How can I dynamically highlight the active menu item in my menu? I believe that adding v-if(selected) and a function might be the way to go in the first template. <template> <MenuTreeView @selected='collapsedMenuSelected' :items=&apo ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

After minifying the JS file, the $http service was not injected into the controller within a component

angular.module("datasView",[]) .component("datasView",{ templateUrl : 'dataview/datasview.template.html', controller : function control($http){ var self = this; $http.get('src/data/issues.json').then(function(res ...

Switching the URL without reloading the page in NEXT.JS

Currently, I am in the process of building an ecommerce store using NEXT.JS and Redux. Within the product listing page, I have incorporated a sorting select dropdown featuring options such as Price Low to High, Price High to Low, and New Arrivals. My goal ...

How can you set the listbox in Sumo Select to always be open?

https://i.sstatic.net/fkiHB.png Is there a way to ensure the listbox is always open by default, as if the user had clicked? ...

Tips for efficiently storing large Twitter profile ids in a Node JS application

I am encountering an issue while trying to store the followers of a few users on Twitter. The followers/ids endpoint provides a list of IDs, but not in the id_str format. I have been attempting to convert these IDs into string format, but when I use large ...

What is the process for displaying images stored in a shared folder using Angular?

<img width="118px" height="180px" src="{{book.imageUri}}" /> book.imageUri="\\someServer\images\9780352347893.jpg" Even though it didn't show up on the Angular page, when pasted into Chrome, the image appeared perfectly. ...

Mastering Angular 4: The ultimate guide to managing multiple classes using ngClass

I want to customize my navigation links to resemble file folder tabs by dynamically adding and removing classes using Angular. When a link is active, it should not have a bottom border to indicate it as the primary tab. Here's a rough starting point: ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...