Reputation: 2675
Hi I have a case where I disable the submit button when entering the form and only enable it when the input box has some text.
<div id="app-id-input-container" ng-form="appIdInput">
<div class="input-group">
<input id="app-id-input" name="appIdInput" ng-click="clearAppIdInput()" class="form-control" type="text" ng-model="appId" pattern="^[AaIi][PpXxNn][0-9]{6}$" maxlength="8" />
<span class="input-group-btn">
<button id="addAppId" class="btn btn-success" ng-click="preferences.appIdInput.$valid && addAppId()" type="button"> <span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<span class="validation-alert" ng-show="appIdError">{{appIdError}}</span>
</div>
I clear the field when a user clicks inside the input box.
$scope.clearAppIdInput = function() {
$scope.appId = "";
};
Even though the scope is empty, the button is not disabled.
This is how I disable the button.
$(document).ready(function(){
$('#addAppId').prop('disabled',true);
$('#app-id-input').keyup(function(){
$('#addAppId').prop('disabled', this.value == "" ? true : false);
});
});
Right now, I can disable the button again by clicking on "backspace" on my keyboard?
How do I disable the button again just when I clear the input field using a click?
Upvotes: 1
Views: 3252
Reputation: 20844
Following Angular way, I would recommend to use ngDisabled
directive:
<button ng-disabled="!appId" id="addAppId" class="btn btn-success"
ng-click="preferences.appIdInput.$valid && addAppId()"
type="button"> <span class="glyphicon glyphicon-plus"></span>
</button>
Though the button will be disabled if $scope.appId
is empty or undefined. No jQuery or any special handlers are needed for that.
Upvotes: 5
Reputation: 302
<button id="addAppId" class="btn btn-success" ng-click="preferences.appIdInput.$valid && addAppId()" type="button"> <span class="glyphicon glyphicon-plus" ng-disabled="!appId"></span></button>
ng-disabled="!appId"
will disable your button when $scope.appId
is empty, undefined or null.
Simple snippet example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.appId = "";
$scope.clearAppId = function(){
$scope.appId = "";
}
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button class="btn btn-default" ng-disabled="!appId">Disable This</button>
<input type="text" ng-click="clearAppId()" ng-model="appId"/>
</div>
</body>
</html>
Upvotes: 0
Reputation: 2199
The field is only checking for disabling when you press a key.
You should call disable after clearing your input:
$scope.clearAppIdInput = function() {
$scope.appId = "";
$('#addAppId').prop('disabled', true);
};
But the answer from dhilt is more angular style and looks clearer.
Upvotes: 1