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
It can be used to get the currently focused element in the document: Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
Use the document. hasFocus() method to check if a window has focus, e.g. if (document. hasFocus()) {} . The method returns a boolean value indicating whether the document or any element in the document has focus.
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.
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');
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With