清除文本输入和禁用按钮onclick Angularjs

时间:2017-10-09 15:15:04

标签: javascript 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">&nbsp;<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);
    });
});

现在,我可以通过点击键盘上的“退格”来再次禁用该按钮吗?

当我通过点击清除输入字段时,如何再次禁用该按钮?

3 个答案:

答案 0 :(得分:5)

按照Angular方式,我建议使用ngDisabled指令:

<button ng-disabled="!appId" id="addAppId" class="btn btn-success"
        ng-click="preferences.appIdInput.$valid && addAppId()" 
        type="button">&nbsp;<span class="glyphicon glyphicon-plus"></span>
</button>

虽然如果$scope.appId为空或未定义,该按钮将被禁用。不需要jQuery或任何特殊的处理程序。

答案 1 :(得分:1)

该字段仅在您按键时检查是否禁用。

清除输入后应该调用disable:

$scope.clearAppIdInput = function() {
    $scope.appId = "";
    $('#addAppId').prop('disabled', true);
};

但是dhilt的回答是更有棱角的风格,看起来更清晰。

答案 2 :(得分:0)

<button id="addAppId" class="btn btn-success" ng-click="preferences.appIdInput.$valid && addAppId()" type="button">&nbsp;<span class="glyphicon glyphicon-plus" ng-disabled="!appId"></span></button>
ng-disabled="!appId"为空,未定义或为空时,

$scope.appId将停用您的按钮。

简单代码段示例:

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

相关问题