Spearfisher
Spearfisher

Reputation: 8783

Check if input has focus

I have an input with a minimum number of characters required. When a user start typing something and then switch to another field without reaching the minimum number of characters required, I want to change the class of a text to turn it to red.

I have tried using this code to detect when the focus change but it is not working:

$scope.$watch(function(){
    return $('#job_desc').is(':active');
}, function(){
    console.log('test');
})

what is the problem?

Many thanks

Upvotes: 7

Views: 14747

Answers (2)

Samuel Ayvazyan
Samuel Ayvazyan

Reputation: 223

You can listen by specific selector also, like this.

function listenForFocus() {
    var el = angular.element( document.querySelectorAll( 'input, select' ) );
    for (var i = 0; i < el.length; i++) {
        var element = angular.element(el[i]);
        element.bind('blur', function (e) {
            console.log('blur');
        });
        element.bind('focus', function (e) {
            console.log('focus');
        });
    }
}

Upvotes: 2

zszep
zszep

Reputation: 4483

If you are using angularjs 1.2 you have two directives to help you to watch if a field has focus: ng-focus and ng-blur. If not, it's quite simple to implement your own directives. The code (plunker):

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
       <script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>

    <script data-require="[email protected]" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <form>
       <input ng-model="name" id="name" ng-focus="focused()" ng-blur="blurred()">
       <input ng-model="name2">
    </form>
  </body>

</html>

and the javascript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.focused = function() {
    console.log("got focus");
  }

   $scope.blurred = function() {
    console.log("lost focus");
  }
});

If on the other hand, you just want validation, look into form validation in angularjs, something like myForm.myInput.$valid. Angularjs sets the ng-valid and ng-invalid classes accordingly.

Upvotes: 11

Related Questions