[英]Clear text input and disable button onclick Angularjs
嗨,我有一種情況,我在輸入表單時禁用了提交按鈕,而僅在輸入框包含一些文本時才啟用它。
<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>
當用戶在輸入框中單擊時,我會清除該字段。
$scope.clearAppIdInput = function() {
$scope.appId = "";
};
即使范圍為空,也不會禁用該按鈕。
這就是我禁用按鈕的方式。
$(document).ready(function(){
$('#addAppId').prop('disabled',true);
$('#app-id-input').keyup(function(){
$('#addAppId').prop('disabled', this.value == "" ? true : false);
});
});
現在,我可以通過單擊鍵盤上的“退格鍵”來再次禁用該按鈕嗎?
當我單擊一下清除輸入字段時,如何再次禁用該按鈕?
按照Angular的方式,我建議使用ngDisabled
指令:
<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>
盡管如果$scope.appId
為空或未定義,該按鈕將被禁用。 不需要jQuery或任何特殊的處理程序。
該字段僅在按下鍵時檢查是否禁用。
清除輸入后,應調用disable:
$scope.clearAppIdInput = function() {
$scope.appId = "";
$('#addAppId').prop('disabled', true);
};
但是dhilt的答案是更多棱角分明的樣式,而且看起來更清晰。
<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"
將在$scope.appId
為空,未定義或null時禁用您的按鈕。
簡單的代碼段示例:
<!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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.