I have an input and a button. I want the button to be disabled when the input is empty or is more than 15 characters long.
HTML
<input type="text" id="addCustomer" ng-model="customerNumber">
<button id="addSingleCustomerButton" ng-disabled="!isValidSingleInput(customerNumber)" ng-click="addCustomer()"></button>
isValidSingleInput
$scope.isValidSingleInput = function(input) {
return (input != undefined && input.length > 0 && input.length <= 15);
}
addCustomer
$scope.addCustomer = function() {
$('#addSingleCustomerButton').button('loading');
// Call service to add customer number to database
CustomerService.add({}, payload, function(data) {
$('#addSingleCustomerButton').button('reset');
$scope.customerNumber = '';
});
}
At the end of the addCustomer function the input field is cleared by setting the scope with $scope.customerNumber = '';.
However, the button is not disabled again after clearing the input. I added a log to the isValidInput function with the result of it and it returns false after clearing the input. So the function is called and it returns the expected value, but it somehow has no effect on the button's ng-disabled.
EDIT: Added function addCustomer
EDIT2: Didn't think it would matter, but the problem is caused by Bootstrap's button.js. If I remove the .button('loading') and .button('reset') it's working. In my eyes this should work anyways because I'm resetting the scope after the button.
can you check to see why it might not be working for you?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.isValidSingleInput = function(input) {
return (input != undefined && input.length > 0 && input.length <= 15);
}
$scope.addCustomer = function(){
$scope.customerNumber = '';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" id="addCustomer" ng-model="customerNumber">
<button id="addSingleCustomerButton" ng-disabled="!isValidSingleInput(customerNumber)" ng-click="addCustomer()">BUTTON</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With