Strategies for detecting when the focus has moved away from a Div

I'm currently developing a dynamic form that generates multiple Divs. My goal is to detect when the focus is lost from an entire div, not just from one input field.

https://i.sstatic.net/YopGs.png

As shown in the image, I have several identical forms and the challenge lies in identifying when a user finishes editing one of the forms.

These forms are dynamically created using an ng-repeat directive.

<fieldset data-ng-repeat="response in responces" ng-init="sectionIndex = $index">
    <div id="customFrom">
    <input type="text" ng-model="response.code" name="" placeholder="Code">
    <input type="text" ng-model="response.rank" name="" placeholder="{{ 'app.forms.responses.rank' | translate }}">
    <input type="text" ng-model="response.value" name="" placeholder="{{ 'app.forms.responses.value' | translate }}">
    <input type="text" ng-model="response.name" name="" placeholder="{{ 'app.forms.createQuiz.fields.name' | translate }}" class="labelTextQuestionCreation">
    <button class="remove"  ng-click="removeResponse($index)" ng-show="deteteResponceOption">-</button>
    </div>
</fieldset>

What's the best approach to trigger an action when a user switches from one form to another? I need to detect when a form (Div) loses focus in order to execute a specific function. Thank you.

Answer №1

After carefully considering your issue, it appears that utilizing ng-model-options is the most effective solution.

For each element with ng-model, include the following attribute:

ng-model-options="{ updateOn: 'blur' }"

This will result in the following code snippet:

<input type="text" ng-model="response.code" name="" ng-model-options="{ updateOn: 'blur' }" placeholder="Code">

By implementing ng-model-options, the model will only be updated when focus is lost on the form field. You can then utilize a $watch statement to monitor any changes to the model.

Within the $watch callback function, you can detect modifications to any attributes of the main array and perform validation to ensure all data is complete before proceeding with your desired functionality.

$scope.$watch('responces', function (newVal, oldVal) {
    // Validation logic for input fields
}, true);

Answer №2

One way I solved the issue was by incorporating a hidden input that specifies the form's index. The value of this input is added to the model since I am using ng-repeat and each row has its own scope. Additionally, I utilized the ng-focus directive to check for focus on an input field. Upon focus, a function named `getSelectedElement(index)` is called. This function checks if the index has changed and updates/inserts the row in the database accordingly. Below is the code snippet for the solution:

HTML

<fieldset  data-ng-repeat="response in responces track by $index" ng-init="sectionIndex = $index">
    <div ng-model-options="{ updateOn: 'blur' }">
    <input type="text" ng-model="response.code" name="" placeholder="Code" ng-focus="getSelectedElement(sectionIndex)">
    <input type="text" ng-model="response.index" ng-init="response.index=sectionIndex" ng-value="sectionIndex" ng-focus="getSelectedElement(sectionIndex)" ng-show="false">
    <input type="text" ng-model="response.rank" name="" placeholder="{{ 'app.forms.responses.rank' | translate }}" ng-focus="getSelectedElement(sectionIndex)">
    <input type="text" ng-model="response.value" name="" placeholder="{{ 'app.forms.responses.value' | translate }}" ng-focus="getSelectedElement(sectionIndex)">
    <input type="text" ng-model="response.name" name="" placeholder="{{ 'app.forms.createQuiz.fields.name' | translate }}" class="labelTextQuestionCreation" ng-focus="getSelectedElement(sectionIndex)">
    <button class="remove" ng-click="removeResponse($index)" ng-show="deteteResponceOption">-</button>
    </div>
</fieldset>

JavaScript

$scope.getSelectedElement=function(index){
 var oldIndex=$scope.responcesSelectedIndex;
 if(oldIndex==-1){
     oldIndex=index;
 }
 $scope.responcesSelectedIndex=index;
 var newIndex=$scope.responcesSelectedIndex;
     if(oldIndex!=newIndex){
        console.log("Update or Create");
        //Perform necessary actions here
    }
}

While not flawless, this approach gets the job done effectively.

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

Regular expression: subpattern without immediate subsequent character

Consider a regular expression that needs to return true for any string containing the substring hello, followed by any string that does not start with ! or multiple instances of !. Here are some examples to clarify: var regExp = /someExpression/; regExp ...

Step-by-step guide for adding an icon to the corner of a Material UI button

Is there a way to position an icon in the corner of a Material UI button in React? Currently, I have the icon next to the title but I would like to move it to the lower right corner of the button. Any suggestions on how to achieve this? Thank you! export ...

Is the AngularJS Date property model sending an incorrect value to the server?

There are some puzzling things I am trying to figure out. When using datetimepicker, the Date and time selected appear correctly on the screenshot. The value in the textbox is accurate The model's value in console is correct (but hold on a second... ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

What is the best way to extract hover-box information from an ajax website with Python?

Attempting to extract the dimensions for each cell on a map from this AJAX site, where details only appear when hovering over the cells has proven unsuccessful so far. Using Python selenium webdriver and phantomJS did not yield any data when trying to loa ...

What could be the reason behind the validation failure of this Javascript code?

After implementing your recommendation, this is my current status: <script> function tick() { const React.element = ( '<div><marquee behavior="scroll" bgcolor="lightyellow" loop="-1" width="100%"> <i> <font color ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Transferring a variety of PHP arrays to JavaScript upon successful AJAX completion

Struggling with passing arrays from a PHP page to JavaScript using AJAX requests. I need to transfer data from multiple PHP arrays to JavaScript and although I understand that json_encode can be used for this purpose, I'm finding it difficult to imple ...

Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/c ...

@keyframes shimmering-fade

I'm attempting to create a text animation effect (please see video) but I'm struggling to find the solution!! Can someone assist me with this? Should I use JavaScript for a better result? h1.fadeinone { animation: fadeinone 10s;} h1.fadeintwo ...

Which method is better for HTML5/JavaScript GeoLocation: Passing data to a callback function or suspending an async call using promises?

Trying to figure out how to utilize HTML5/Javascript Geolocations effectively for passing location data to an ajax call and storing it in a database. The main challenges I'm facing are the asynchronous nature of the Geolocation call and issues with va ...

Rotating Images with jQuery using the 'jQueryRotate' extension

Trying to create a hover effect where one div triggers the rotation of an image in another div. Experimenting with the jQueryRotate plugin found at http://code.google.com/p/jqueryrotate/ Check out my code on jsFiddle. The green square is rotating with CS ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Nodejs: code functions properly at my residence, but encounters ECONNREFUSED error when executed in the workplace

Completely new to JavaScript and Node.js, I decided to follow a guide on web scraping with Node.js from . The code worked perfectly at home, but when I tried to implement it at work, I encountered a persistent issue. Error: connect ECONNREFUSED at errnoEx ...

Tips on resolving the Warning message: "The event handler property `onExited` is a known property in StatusSnackbar component, but it will

When using the StatusSnackbar component, I encountered a warning about a known event handler property onExited. How can I resolve this issue? Component: import Snackbar from '@material-ui/core/Snackbar' import { withStyles } from '@material ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...

Tips for achieving a gradual shadow effect on edges in THREE.js

I have come across some 3D scenes where I noticed a subtle gradient shadow near the edges of objects. This seems to enhance the definition between the two faces. How can we achieve this effect? Is it a result of shadow technology or light reflection techni ...

Encountering difficulties in compiling Dynamic HTML with the $compile function

I'm attempting to incorporate dynamic HTML into my code with the following lines: var el = $compile('<a ng-controller=\"tableController\" ng-click=\"open\">...ReadMore</a>')($scope); But I'm encounterin ...

An issue has occurred with the HTTP request to a PHP file in Angular

When attempting to send an http request to my php file, I encountered the following error message Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":" ...