In this article I will explain with an example, how to enable or disable Button based on TextBox (INPUT) value using AngularJS.
This article will illustrate how to enable or disable Button (Submit Button) on KeyUp event of TextBox (INPUT) using the ng-keyup and ng-disabled directive in AngularJS.
Enable or Disable Button based on TextBox (INPUT) value 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 and a Button. 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 TextBox is assigned ng-keyup directive. When User inputs a value in TextBox, the EnableDisable function of the Controller gets called.
Inside the function, the value of the IsDisabled variable is set to false if the TextBox contains some value i.e. it is not blank and IsDisabled variable is set to true if the TextBox is empty or blank.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
//Initialize the value to Blank.
$scope.PassportNumber = "";
//This will disable the Button by default.
$scope.IsDisabled = true;
$scope.EnableDisable = function () {
//If TextBox has value, the Button will be enabled else vice versa.
$scope.IsDisabled = $scope.PassportNumber.length == 0;
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Passport Number:
<input type="text" id="txtPassportNumber" ng-model="PassportNumber" ng-keyup = "EnableDisable()" />
<hr />
<input type="button" value = "Submit" ng-disabled="IsDisabled" />
</div>
</body>
</html>
Screenshot
Demo
Downloads