Please ensure you have selected at least one item before submitting the form

I have been working on validating a form using a combination of bootstrap and angularjs. The form includes two groups of checkboxes that need to be validated. It is required for the user to select at least one checkbox from each group in order for the Submit button to be enabled and for the values to be submitted.

Here is a demo showcasing this functionality: https://plnkr.co/edit/m5erCJINS1sj70FxInd4?p=preview

In the provided demo, the user must choose at least one option from the RED or BLUE group and one option from the Mac1 or Mac2 group in order to enable the SubmitValue button and submit the data.

Sample code snippet:

<form name="eltForm">
    <h4>--FORM VALIDATION--</h4>
    <div class="btn-group" name="color">
        <label class="btn btn-primary btn-sm" ng-model="model1.prod1" uib-btn-checkbox="prod1">RED
            <span class="glyphicon glyphicon-info-sign"></span>
        </label>
        <label class="btn btn-primary btn-sm" ng-model="model1.prod2" uib-btn-checkbox="prod2">BLUE
            <span class="glyphicon glyphicon-info-sign"></span>
        </label>
        <div ng-show="eltForm.$submitted || eltForm.color.$touched">
            <p class="error-mesg" ng-show="eltForm.color.$error.required">Please Select the Color.</p>
        </div>
    </div>
    <div class="btn-group" style="margin: 0 3px;padding: 5px;" name="machines">
        <label class="btn btn-primary btn-sm" ng-model="model2.item1" uib-btn-checkbox="item1">Mac1
            <span class="glyphicon glyphicon-info-sign"></span>
        </label>
        <label class="btn btn-primary btn-sm" ng-model="model2.item2" uib-btn-checkbox="item2">Mac2
            <span class="glyphicon glyphicon-info-sign"></span>
        </label>
        <div ng-show="eltForm.$submitted || eltForm.machines.$touched">
            <p class="error-mesg" ng-show="eltForm.machines.$error.required">Please Select the Machines.</p>
        </div>
    </div>
    <div class="btn-group">
        <button type="button" class="btn btn-primary btn-xs" style="margin: 13px;" ng-click="submitValue()" ng-disabled="myForm.$invalid">SubmitValue</button>
    </div>
</form>

Answer №1

 $scope.submitValue = function(){
   if(($scope.model1.prod1 || $scope.model1.prod2 )&& ($scope.model2.item1 || $scope.model2.item2))
   alert('Hi');
 }

please update your controller with the code provided above.

visit this link for reference

Answer №2

To enable/disable a button in Angular, add an `ng-disabled` attribute to the button element and bind it to a field on the `$scope`. For example, set `$scope.buttonDisabled = true;` to disable the button. Additionally, use `ng-click` on a label or button to check the model value based on conditions and update the `$scope.buttonDisabled` accordingly.

var app = angular.module('app', ['ui.bootstrap']);
app.controller('dataCtrl', function($scope, $uibModal) {
  'use strict';
  $scope.buttonDisabled = true;
  $scope.model1 = {
    prod1: false,
    prod2: false,
  };
  $scope.model2 = {
    item1: false,
    item2: false,
  };

  $scope.clicked = function() {
    if (($scope.model1.prod1 || $scope.model1.prod2) && ($scope.model2.item1 || $scope.model2.item2)) {
      $scope.buttonDisabled = false;
    }
  }

  $scope.submitValue = function() {
    if (($scope.model1.prod1 || $scope.model1.prod2) && ($scope.model2.item1 || $scope.model2.item2)) {
      alert('VALID');
    }
  }
});
.btn span.glyphicon {
  opacity: 0;
}

.btn.active span.glyphicon {
  opacity: 1;
}
<!DOCTYPE html>
<html>

<head>
  <link data-require="bootstrap-css@*" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="66070801130a0714480c15265748534856">[email protected]</a>" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.4.js"></script>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css" />
</head>

<body ng-app="app" ng-controller="dataCtrl">

  <form name="eltForm">
    <h4>--FORM VALIDATION--</h4>
    <div class="btn-group" name="color">
      <label class="btn btn-primary btn-sm" ng-click="clicked()" ng-model="model1.prod1" uib-btn-checkbox="prod1">RED
<span class="glyphicon glyphicon-info-sign"></span>
    </label>
      <label class="btn btn-primary btn-sm" ng-click="clicked()" ng-model="model1.prod2" uib-btn-checkbox="prod2">BLUE
    <span class="glyphicon glyphicon-info-sign"></span>
    </label>
      <div ng-show="eltForm.$submitted || eltForm.color.$touched">
        <p class="error-mesg" ng-show="eltForm.color.$error.required">Please Select the Color.</p>
      </div>

    </div>
    <div class="btn-group" style="margin: 0 3px;padding: 5px;" name="machines">
      <label class="btn btn-primary btn-sm" ng-click="clicked()" ng-model="model2.item1" uib-btn-checkbox="item1">Mac1
    <span class="glyphicon glyphicon-info-sign"></span>
    </label>
      <label class="btn btn-primary btn-sm" ng-click="clicked()" ng-model="model2.item2" uib-btn-checkbox="item2">Mac2
    <span class="glyphicon glyphicon-info-sign"></span>
    </label>
      <div ng-show="eltForm.$submitted || eltForm.machines.$touched">
        <p class="error-mesg" ng-show="eltForm.machines.$error.required">Please Select the Machines.</p>
      </div>
    </div>
    <div class="btn-group">
      <button type="button" ng-disabled="buttonDisabled" class="btn btn-primary btn-xs" style="margin: 13px;" ng-click="submitValue()" ng-disabled="myForm.$invalid">SubmitValue</button>
    </div>

  </form>
</body>

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

Is it possible to dynamically set the maximumSelectionLength in a select2 dropdown?

In my HTML, I have two select elements. One is for multiple selection of items in a dropdown and the other is for adding tags. If the number of selected items is 3, then users should only be allowed to add 3 tags - no more and no less. $(".js-example-b ...

The dimensions of the box are not predetermined by the size of the photo

I'm attempting to develop a photo gallery that emulates the style of (using the Unsplash API -> ) However, the size of the container box does not adjust properly with the photos. <div className="imageGrid__container"> <di ...

Exploring AngularJS with Filtering for Advanced Search Results

Currently, I have a search box that successfully searches values in a table using my code. <tr ng-repeat="b in bugs | filter:searchText"> Now, I want to take it one step further by allowing users to search specific columns if they include a colon i ...

Ways to Determine the Height and Width of an Image Once it has been Adjusted for a View

Is there a way to retrieve the height and width of an image after it has been resized for a view? I have images that may vary in original dimensions, but users can resize them as needed. For example, this code from the console gives the client height: do ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

``In Internet Explorer, the function to swap the image source when hovering over the parent element

I'm trying to make it so that when I hover over the parent (Li) tag with my mouse, the src attribute of the child img tag changes. This code works correctly in Chrome but not in Firefox and Internet Explorer. <li class="player"> . . //some c ...

Getting row data in datatables after a button click: A step-by-step guide

Could somebody provide assistance with retrieving a single row of data on a click event? This table is dynamically populated after the AJAX call's Success function is executed <div class="table-responsive table-wrap tableFixHead container-flu ...

Encountering a TypeError when implementing $cookies in a controller: undefined function error occurs

UPDATE: RESOLVED ISSUE It turns out that I mistakenly thought ngCookies was a built-in part of angular.js, but in reality it is a separate service. The problem was with my bower.json file which referenced angular 1.4beta while loading angular-cookies for ...

Exploring the depths of asynchronous calls in AngularJS with nested functions

Currently, I'm tackling a small project with AngularJS and finding myself tangled in multiple asynchronous calls that are starting to become chaotic. I know there must be a more efficient way to handle these calls, but I'm unsure of the best appr ...

What is the proper way to invoke a function that is part of a child component as a property in a React application?

In my app.js file, I have included a unique component called "SigningComponent" with the following code: onSign = () => { this.setState({ route: "home" }); }; registerFunction = () => { this.setState({ route: "registration" }); }; render() { ...

There seems to be an issue with the DownloadDir functionality of the node-s3-client library, as

I am currently using a node s3 client library called 'node-s3-client' for syncing directories between S3 and my local server. As per the guidelines provided in the documentation, here is the code I have implemented: var s3 = require('s ...

"Successfully implementing AJAX POST functionality, but encountering issues where callbacks are not triggering

I have gone through numerous posts addressing this issue and attempted various solutions, however, none seem to work for me. My AJAX POST function correctly adds the email to my mailing list, but the success and error callbacks are not consistently firing, ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

Tips for sending an ID to a path link in React Js

Can anyone assist me in setting up a path for a component like this "/products?id=uniqueId" in my React Js Project? The unique id is retrieved from the database and varies depending on the product chosen. Below is an excerpt of my code: CodeSandbox App.j ...

Adjust the style of an element when hovering over a different element

Below is the HTML code in question: <div> class="module-title" <h2 class="title" style="visibility: visible;"> <span>Spantext</span> Nonspantext </h2> </div> I am looking to change th ...

Ways to display certain JSON elements

I'm attempting to retrieve a specific part of a JSON file through AJAX and display it in an HTML div. I only want to show a certain object, like the temperature. Here is the AJAX code: $(function () { $.ajax({ 'url': 'http://ap ...

How can ReactJS continuously dispatch promises after a set interval?

Within my React component, I am invoking an action in ComponentDidMount() as shown below: componentDidMount() { const { actions } = this.props function save_project_continuously() { console.log("inside") actions.sa ...

Tips for updating the css class for multiple DOM elements using jQuery

I am currently attempting to modify the class property of a specific DOM element (in this case, a label tag) using jQuery version 1.10.2. Here is the code snippet I have written: var MyNameSpace = MyNameSpace || {}; MyNameSpace.enableDisableLabels = (f ...

"Troubleshooting: Why isn't AngularJS $http.post sending my data

Feeling frustrated with my experience using AngularJS and Laravel 5.2. I'm trying to make a standard $http post request: APIservice.saveArticle = function ( oArticle, callback ) { var message = 'Hello World!'; $http({ metho ...

Unable to assign value to Angular scope variable

Currently, I am delving into Angular JS as a learner. My attempt at using $http to set the corresponding value to the scope variable seems to be failing. Below is a snippet of the HTML code I am working with: <div ng-app="fileapp" ng-controller="myctl" ...