Search code examples
angularjs-scope

Check if input field is empty in the angularjs script


I have a html code, how can i check if the input field is empty in the script. Is there any way we can use scope to check this. I know we have form validation in angular but am just curious.


Solution

  • To achieve expected result, you can use ng-keyup function

    HTML:

    <html lang="en">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="formCtrl">
      <form>
        First Name: <input type="text" ng-keyup="check()" ng-model="firstname">
      </form>
    </div>
    
    </body>
    </html>
    

    JS:

    var app = angular.module('myApp', []);
    app.controller('formCtrl', function($scope) {
        $scope.check= function(){
          var x =$scope.firstname;
          if(x.length==''){
            alert("input empty");
          }
        };
    });
    

    Codepen- http://codepen.io/nagasai/pen/qNPJZV