How to disable a button when there is no input in a text field

1.4k views Asked by At

I want the search button to be disabled if there is no entry in the search field;

In my html file I have:

<div class="form-group">
    <input type="text" class="form-control" ng-model"searchinput">
</div>
<button type="submit" class="btn" ng-click="search()" ng-disabled="disabled"> Search</button>

In my controller, I have:

if ($scope.searchinput == ""){  
     $scope.disabled = true;
}

This is not working. What am I doing wrong?

3

There are 3 answers

0
Ajinkya Dhote On

Calculate the length of searchinput if length is less than zero then simply disable

isButtonDisable = function() {
   $scope.searchinput.length == 0 ? true : false;
}

and in your html

<div class="form-group">
    <input type="text" class="form-control" ng-model"searchinput">
</div>
<button type="submit" class="btn" ng-click="search()" ng-disabled="isButtonDisable()"> Search</button>
0
Kunal Gadhia On

Simply Do This :

HTML :

   <div class="form-group">
       <input type="text" class="form-control" ng-model"searchinput">
   </div>
   <button type="submit" class="btn" ng-disabled="!searchinput"> Search</button>    

This will solve your problem.

1
Kunvar Singh On

Try for this:

    <form name="myForm" ng-controller="MainCtrl">
    <input type="text" ng-required="true" name='myName' ng-model='myName'/>
    <span>{{name}}</span>
    <input type="submit" value="Submit"  ng-disabled="myForm.myName.$pristine" />
    {{myForm.myName.$pristine}}
</form>