`Active the button once user checks one or more checkboxes using AngularJS`

I'm working on a project where I have checkboxes and a button. I need to figure out how to activate the button when one or more checkboxes are checked using AngularJS. Can anyone provide some guidance?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<label><input type="checkbox" name="check"> First</label>
<label><input type="checkbox" name="check"> Second</label>
<label><input type="checkbox" name="check"> Third</label>


<br>
<button type="button" disabled ng-model="$scope.btn">active/deactive</button>

Answer №1

Assign the ng-model to checkboxes

<label><input type="checkbox" name="check" ng-model="check1"> First</label>
<label><input type="checkbox" name="check" ng-model="check2"> Second</label>
<label><input type="checkbox" name="check" ng-model="check3"> Third</label>

Then, utilize ng-disabled to toggle button's state

<button type="button" ng-disabled="!check1 && !check2 && !check3" ng-model="$scope.btn">activate/deactivate</button>

Answer №2

Utilize the ng-disabled directive on the button to dynamically add the disable attribute.

Take a look at the following example where the checkboxes are linked to their respective properties on the controller's scope using the ng-model directive for two-way data binding in AngularJS.

Keep in mind: If you have a complex condition to evaluate in the view, consider creating a function and calling it in the view using an appropriate directive.

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);
  
  function DefaultController() {
    var vm = this;
    vm.disableButton = disableButton;
    
    function disableButton() {
      if (vm.first || vm.second || vm.third) {
        return false;
      } else {
      return true;
      }
    }
  }
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <label><input type="checkbox" name="check" ng-model="ctrl.first"> First</label>
    <label><input type="checkbox" name="check" ng-model="ctrl.second"> Second</label>
    <label><input type="checkbox" name="check" ng-model="ctrl.third"> Third</label>
    <br>
    <button type="button" ng-disabled="ctrl.disableButton()">active/deactive</button>
  </div>
</div>

Answer №3

  1. Utilize ng-model to store checkbox values and incorporate them in ng-disabled="!(checkboxValue1 || ch...)"

  2. Implement ng-model to save values and ng-required="!checkBox2Value && !checkbox3Value" for the checkboxes. Surround the checkboxes with a form tag and use ng-disabled="formName.$invalid"

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

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Managing the re-triggering of a function within useEffect upon the user clicking the "Back Button" in a React application

Is there a way to prevent the loadUserPosts() function from being called again when the user clicks the 'back button' on their browser? It seems like the isLogged useState is being changed when the back button is clicked. The loadUserPosts funct ...

Is there an Angular Profile service offering getter and setter properties?

Can a singleton Angular service be created with getters and setters along with logic implementation? I was provided with the following code snippet and tasked with replicating it in an Angular service. Although it may seem straightforward, I'm finding ...

Encountering an error message of "Cannot POST" while trying to send data through a REST client application

Upon my attempt to add a new entry into the Doctors database I created, I encountered an error that has left me perplexed. This is how my server.js file appears: const express = require('express'); const bodyParser = require('body-parser&a ...

Error: Unable to call the 'model' function on the 'users' object in Mongoose due

I'm attempting to implement Mongoose's method for defining models in a separate document from their schemas, especially when dealing with multiple databases. Here's the example provided by Mongoose's Docs for User.js: const userSche ...

Tips for detecting when a browser is closing in a web application that is integrated with a master page

Currently, I am working on a web application that uses a master page. I need to be able to detect when the user is closing the browser so that I can raise an event to clean up session variables. I attempted using the unload JavaScript event, but it seems ...

Setting the default value to null or 0 in a Select dropdown in Angular 7

There is a select dropdown code that may be hidden in some instances. When the select dropdown is hidden, I want to ensure null or 0 is sent instead of an empty value when saving the form. How can I achieve this? <div class="col-md-4" [hidden]="!cpSe ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

Combine two objects and discard any duplicate keys

I have two objects named original and custom. My goal is to merge the content from custom into original, but only update the keys in original that are also present in the custom object. Here is an example scenario: var original = { coupon: { ...

Eliminating documents subsequent to file upload

I need to send in my application and upload the necessary file for the submission. However, I can only upload the files after the application is successfully submitted. To achieve this, I have included the upload function within the success callback of the ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

Tips for embedding svg within ion-content

My application is developed using Angularjs and ionic framework, incorporating cordova for hybrid mobile capabilities. However, when attempting to display svg content received from the backend, the expected diagram does not render properly. This is an exa ...

When I click the login button, a .ttf file is being downloaded to my computer

I have encountered an issue with my web application where custom font files in .ttf, .eot, and .otf formats are being downloaded to users' local machines when they try to log in as newly registered users. Despite attempting various solutions, I have b ...

When using jQuery, adding a class does not always trigger CSS animation

Currently facing a peculiar issue. I am utilizing jQuery to load articles from JSON and would like to dynamically add a class of 'animate' to each loaded element. $.each(jsonArticles, function (i, article) { var $articleHTML = $( ' ...

Retrieve particular JSON information on a single webpage by selecting an element on a separate page

My goal is to fetch specific information from a JSON file and display it on different HTML pages by clicking a button. I will achieve this using jQuery and plain JS. For the first HTML page, I want to show all products from the JSON in an element with id= ...

Having trouble making "jQuery.inArray" function properly in my code

Recently, I made a small interaction where list items are displayed and rotated when clicked - check it out here: http://jsfiddle.net/S79qp/430/ Lately, due to compatibility issues with IE8, I had to switch from using .indexOf() to jQuery.inArray. However ...

Is there a way to retrieve the value of an element by clicking on its corresponding button using MUI framework?

I am working on a dashboard feature where I need to update the status by clicking on it. However, I am facing an issue with changing the state value upon clicking. Here is my component: <MenuItem> <Button fullWidt ...

Ways to display scroll bar when hovering the mouse pointer?

When visiting the website YouTube, you may notice that their sidebar scrollbar becomes visible as soon as your mouse moves over it. I've been attempting to achieve this effect on my own div, but currently, the scrollbar only appears once I start scrol ...

JQuery cannot target content that is dynamically inserted through an Ajax request

When I use an ajax call to pass dynamically generated html, such as in the example below: var loadContent = function(){ $.ajax({ url: '/url', method: 'GET' }).success(function (html) { $('.con ...