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

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

Exploring the nuances of receiving responses with NextJs, Nodemailer, and Fetch

Currently in the process of constructing a basic contact form with Next.js, nodemailer, and fetch. Despite successfully sending emails from the frontend form to the designated email account, the network shows the contact submission as pending. After approx ...

How can I only replace every second occurrence in a JS string?

Looking for help with JavaScript: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I thought the result would be '', but it's showing 'a a' instead. Can someone explain what I'm missing? To clarify, I want to r ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully funct ...

React Resize Detection: Handling Window Resize Events

Is there a more efficient way to listen for the window resize event in react.js without causing multiple callbacks? Perhaps a React-oriented approach (like using a hook) to achieve this? const resizeQuery = () => { console.log("check"); if ( ...

Is there a better method to determine the width when utilizing the jQuery UI resizable feature for improved efficiency?

I'm currently working on a website that features a resizable sidebar. I want the icons and text within the sidebar to shrink proportionally when the user resizes it. Right now, I have implemented an if statement to check if the sidebar's width fa ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...

Once an AJAX call is made, the state of a React component changes but fails to trigger a

In this section, users have the opportunity to comment on posts. Once the data is received and verified on the server side, I attempt to update the value of this.state.comments. However, there is an issue where the comment section in the component does not ...

JavaScript button for displaying and hiding all content in one click

I came across a tutorial on W3Schools that showed how to create collapsibles, and I thought it would be great to have buttons that could expand or collapse all at once. I've been trying to implement this feature using the code provided in the tutorial ...

When accessing nested objects in Props in Vue.js, an error may occur if the property of null/undefined

When I make an axios call, I receive an object which I pass to a child component. However, when I attempt to loop through the object in the child component to access a property of another nested object, I encounter an issue where the property is showing as ...

Utilizing Vue.js with Firestore: Retrieve information from Firestore without rendering any data on the screen

When attempting to display my data from Firestore, I encountered an issue where the data was retrieved successfully when hovering over the <td> tag but not actually displayed. Here is my file for fetching data from Firestore: <template> & ...

Is it possible to send a function object as an argument to an Angular directive?

I've encountered an issue: I want to create a custom directive that operates as follows: <input type="text" ng-model="prefix" prettified="angular.lowercase"> <input type="text" ng-model="firstName" prettified="capitalize"> <input type= ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...

An error occurred while attempting to reset your password on Parse.com (JS SDK) due to an

I am having trouble resetting my password in my angularjs App. I am utilizing Parse (js SDK) as the backend. Even though I am following the documentation and using Parse.User.requestPasswordReset, I keep encountering error 125 which states invalid email ad ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

Is it possible to utilize a JavaScript framework within a Chrome extension?

Currently, I am developing a chrome extension that adds a toolbar to the DOM dynamically. In order to find, attach, and manipulate elements, I have been using CSS selectors in JavaScript. However, this approach has proven to be fragile as any changes made ...

What is the best way to retrieve information from an external JSON file using HTTP?

//example module.factory('$information', function() { var info = {}; info.items = [ { title: '1 Another Item Title', label: '6h', desc ...

Encountering error code 2064 without any clear explanation in sight

Hey, I'm currently facing an issue while uploading values to a MySQL table from Node.js. The error 1064 keeps popping up, indicating that the query is badly formatted. However, I can't seem to pinpoint the exact problem. Here's the query in ...