Michael Michael - 1 month ago 17
AngularJS Question

How to disable or enable button according to if text boxes empty or not?

I work on my angularjs projerct.

I have button in my template and two input text elements.

The button have to be enabled only when two input boxes has some string.

Here is HTML code:

<form id="loginform" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" ng-model="UserName" placeholder="UserName">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="text" class="form-control" ng-model="Password" placeholder="Password">
</div>

<div style="margin-top:10px" class="form-group pull-left">
<div class="col-sm-12 controls">
<input type="button"
class="btn btn-success"
value="enter"
ng-click="inspectorArea.verify(UserName,Password)"
ng-disabled="(UserName == null || Password == null)">
</div>
</div>
</form>


and here is working plunker.

Using this row
ng-disabled="(UserName == null || Password == null)
in input button element I disable or enable button.

But it not working properly, you can see from plunker-example, button is enabled only when text boxes has string only for first time, if I remove string from one of the texts box elements the button is enable while I want them to be disalbled.

Any idea how can I disable button if at least one of the text boxes is empty?

Answer

Initially UserName and Password are null. So it will work. But when you type something and delete, they become empty and that's why it didn't work.

I have modified it to check the truthiness.

<input type="button" 
                       class="btn btn-success" 
                       value="enter" 
                       ng-click="inspectorArea.verify(UserName,Password)" 
                       ng-disabled="(!UserName || !Password)">