In this article I will explain with an example, how to enable or disable Button when CheckBox is checked or unchecked in AngularJS.
This article will illustrate how to enable or disable Button on CheckBox click i.e. checked – unchecked or selected – unselected using ng-disabled directive in AngularJS.
Enable Disable Button when CheckBox is checked unchecked using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML Markup consists of an HTML TextBox, Button and a CheckBox. The HTML Button has been assigned ng-disabled directive.
The value of ng-disabled directive has been set using the variable IsDisabled which is initially set to true and hence the HTML Button is disabled when page loads.
The CheckBox has been assigned ng-change directive. When the CheckBox is clicked i.e. checked – unchecked or selected – unselected, the EnableDisable function of the Controller gets called.
Inside the function, the value of the IsDisabled variable is reversed i.e. if it is true then it set to false and vice versa. This makes the HTML Button enabled or disabled when the CheckBox is clicked i.e. checked – unchecked or selected – unselected.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
//This will disable the Button by default.
$scope.IsDisabled = true;
$scope.EnableDisable = function () {
//If Button is disabled it will be enabled and vice versa.
$scope.IsDisabled = !$scope.HasPassport;
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<label for="chkPassport">
<input type="checkbox" id="chkPassport" ng-model="HasPassport" ng-change="EnableDisable()" />
Do you have Passport?
</label>
<hr />
<div>
Passport Number:
<input type="text" id="txtPassportNumber" />
<input type="button" id="btnValidate" value="Validate" ng-disabled="IsDisabled"/>
</div>
</div>
</body>
</html>
Screenshot
Demo
Downloads