Verify whether the input is currently being focused on

My current issue involves an input field that requires a minimum number of characters. If a user begins typing in the field but then switches to another without meeting the character requirement, I would like to change the text color to red.

I attempted using the following code to detect when the focus changes, but it does not seem to be functioning as expected:

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

Could you please advise on what might be causing this problem?

Thank you in advance!

Answer №1

For those utilizing angularjs 1.2, there are two directives available to assist in monitoring if a field has focus: ng-focus and ng-blur. If these are not applicable, it is relatively easy to create custom directives. View the code snippet on (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="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b5a555c4e575a491551487b0a15091543">[email protected]</a>" 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>

The corresponding javascript portion:

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 validation is the primary concern, consider exploring form validation in angularjs, specifically using something like myForm.myInput.$valid. Angularjs automatically assigns the ng-valid and ng-invalid classes based on validation status.

Answer №2

To enhance your listening experience, you can also target specific selectors like so.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to refine data using multiple criteria

I have a list of alarm data that I need to filter based on specific conditions. If there are multiple alarms of type "pull_Alarm" and "emergency_alarm" in the same location, I want to prioritize the "emergency_alarm". Here is my list: [ { ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

Changing the name of '_next' to 'next' within the output folder: NextJS

While developing my NextJS chrome extension, I encountered an issue when trying to 'load unpacked' extension. An error message popped up stating that "Cannot load extension with file or directory name _next. Filenames starting with _ are reserved ...

Using Jquery to activate a vertical scrolling bar

Within my div, I have a tree view that extends beyond the size of the div, causing a vertical scroll bar to appear on the right side. When users click a button outside of the div, I want the page to scroll to a specific item within the div (which I know th ...

Checkbox with an indeterminate state in Angular

I'm currently working on updating an AngularJS (1.5) setup where a parent checkbox becomes indeterminate if one of its children is selected, and all the children are selected if the parent is selected. My main challenge lies in converting the old ES5 ...

Having trouble accessing a section of my website that uses JQuery Mobile and tags

I'm encountering a small issue and I'm not sure how to resolve it. The problem I'm facing is with a HTML5 code containing different pages (tags with ids). I'm utilizing Jquery Mobile to switch between these pages using buttons. Strangel ...

Unable to install npm package from git source

I am attempting to install a package from a git repository that I had previously forked. Here is the command I tried: npm i catsaredoomed/invest-openapi-js-sdk --save-dev Unfortunately, I encountered this error message: npm ERR! prepareGitDep 2> npm W ...

Application utilizing Meteor to connect with external websites or applications

Hey everyone, I'm in the process of developing an application that features a directory of stores. One key requirement is that each store has a unique view created with either Flash or JavaScript. The special view components have already been develope ...

PHP not receiving values when making an AJAX POST request

My AJAX file below is where I pass all the values from my text boxes and post them to edu.php. In edu.php, I intend to update two tables - details and test. However, nothing seems to be updating in my database. When I checked the values with var_dump, the ...

"Implementing React to dynamically load and update value in component, enabling user interaction with the

As a newcomer to the world of React (16.4.2), I am trying to grasp its functionality without delving into Redux just yet; my focus is solely on understanding the core React library. In my application, there is an input component called RangeInput, which r ...

What strategies can be utilized to address the absence of an element in an array iteration that is currently ongoing?

Currently, I am looping through an array of strings using forEach() method to check if each element's length is even or odd. If the length is even, I am removing it using splice(). Although my conditions seem correct, when I look at the input and out ...

How can I delete a pathway in paper.js?

Is it possible to create a new path using the canvas globalCompositeOperation set to 'destination-out'? If so, how would I go about doing this? I have observed that Item has a blendMode property which can be found at . However, experimenting wit ...

Update the text in a personalized dropdown menu when an option is chosen

After spending some time working on a customized dropdown with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option: window.onload = () => { let [...opt ...

Tips for preventing the need to reload data from the server every time sorting or paging is done using ngtable

I have implemented ngtable (1.0.0) to display data fetched from the server side in my development project. Here is a snippet of my controller js: ristoreApp.controller("fmCtrl", ['$scope', '$filter', 'fmFactory', 'Ng ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

How can I customize a default button in HTML to hide the selected option from the dropdown menu?

Hey there! I'm currently working on a website that needs to be bilingual, with Spanish as the default language. I want to include a dropdown button that allows users to translate the content into English. Here's what I've tried so far: ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

Filtering Markers using Angular-Leaflet-Directive and a Personalized Filtering System

I'm currently working on implementing the Angular-Leaflet Directive and facing challenges in filtering the markers based on data from an input text box and the marker object's data property. Despite multiple attempts, I keep running into an infin ...