Trigger a function when the browser automatically populates an input field

I am attempting to trigger a function that can detect if the browser has autofilled a field and then add a specific class to it.

After finding a thread with a solution that mostly works, mentioned here:

Here is how I implemented it:

$.fn.allchange = function (callback) {
    var me = this;
    var last = "";
    var infunc = function () {
        var text = $(me).val();
        if (text != last) {
            last = text;
            callback();
        }
        setTimeout(infunc, 10);
    }
    setTimeout(infunc, 10);
};

$(".input").allchange(function () {
    $('.input').addClass('not--empty');
});

The issue I am facing is that I have another function in place that checks for input changes on blur and adds a class accordingly. However, the above function is causing the class to be added to all instances of '.input'.

I believe the solution lies in triggering the function only on the autofilled element. But when I try using the following code snippet, it does not yield the desired outcome:

$(".input").allchange(function () {
    $(this).addClass('not--empty');
});

Any suggestions on how to make this work correctly?

EDIT: To provide more context, I've included an image below showcasing the scenario:

https://i.stack.imgur.com/tLO8s.png

Answer №1

After some experimentation, I stumbled upon a surprisingly straightforward solution that might not be universally compatible but functions perfectly on the latest versions of Chrome, Firefox, and Safari – exactly what is needed for this specific case.

setTimeout(function() {
    $('.input:-webkit-autofill').each(function() {
        var element = $(this);
        $(element).addClass('not--empty');
    })
},100);

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

Navigating to a form within an Angular-UI uib-tab

Is it possible to access a form within a uib-tab for validation purposes? To see an example, check out this plunker: http://plnkr.co/edit/8hTccl5HAMJwUcHEtnLq?p=preview While trying to access $scope.forminside, I found that it's undefined (referring ...

jQuery/JSON Error: Unexpected character encountered during parsing

I am currently working on MVC4 and I am attempting to transfer data from a view to a controller using JQuery and JSON. The objective is to extract the values of checkboxes within a grid. Here is the code snippet: <script type="text/javascript"> func ...

Place a div at the bottom of a flexbox while adding some padding around it

Here's what I'm dealing with: .flex-container { display: flex; justify-content: center; padding: 5%; position: relative; } .box1 { position: absolute; bottom: 0; width: 100%; height: 100%; } <div class="flex-container"> ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

A guide on incorporating text into a file utilizing JSP within HTML

I am working on a project that includes a JSP file and a .txt file. The JSP file contains a text field and a button, where the user can enter a text and click the button to store it in the .txt file. I have provided my code below, but I seem to be missin ...

You can use AJAX, JQuery, or JavaScript in PHP to upload a total of 7 files by utilizing 7 individual file input

My client has a unique request - they want to be able to upload a file in PHP without using the traditional <form> tag or a submit button. While I am familiar with file uploads in PHP, I am unsure of how to achieve this without utilizing the <for ...

jQuery Extends the loop with the picture

I currently have an animation that goes from the bottom to the top but I want it to loop smoothly without abruptly starting over. Is there any way to achieve this? JavaScript Code var ticker = $('#ticker'); var container = $('#ticker > ...

Continuously send AJAX requests using jQuery until the files have been found

Does anyone know how to continuously listen for an AJAX response from a server-side file using jQuery? The issue arises when the file is only generated after a post request is made from another computer or browser. I need a solution that prevents a 404 e ...

Error: Trying to call an undefined function

Having trouble with an error on this line: $("#register-form").validate. Can anyone offer assistance? Furthermore, if I write this script, how should I incorporate it into the form? Will it function without being called? <script type="text/javascript ...

Update the div on the current page using externally retrieved information

Once again, I find myself stuck on a problem. Allow me to explain. Within this div, I have retrieved data using HTML SIMPLE DOM from another site. Like so: <div id="data">.....</div> Currently, the data refreshes whenever the user reloads th ...

Code in JavaScript using VueJS to determine if an array includes an object with a certain value in one of its elements

I have a scenario where I need to address the following issue: I have an Object with a property called specs. This property consists of an Array that contains several other Objects, each having two properties: name value Here is an example of what my o ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Stop the submission of a form in jQuery if a file with the same name already exists

Currently, I am utilizing MVC3 and have a form containing a file upload feature. My goal is to prompt the user for confirmation if the uploaded file already exists on the server. To achieve this, I have implemented a jQuery method within the form submit fu ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

Run audio player in the background with Google Chrome Extension

I am working on an extension and I want to have a page with an audio player that continues to play even when I click outside of the extension. I tried using the "background" attribute in the manifest file, but it seems to only work with javascript files. ...

Can you explain the role of the %GetOptimizationStatus function within a JavaScript file executing in Node.js?

Currently, I am delving into an article that discusses optimization strategies and includes the following code snippet: //Function that contains the pattern to be inspected (using an `eval` statement) function exampleFunction() { return 3; eval(&a ...

What is the best way to merge an array into a single object?

I have an array object structured like this. [ { "name": "name1", "type": "type1", "car": "car1", "speed": 1 }, { "name": &q ...

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...

Get a CSV file through EmberJs

I have been experimenting with various function calls, but I am unable to figure out how to initiate a CSV download in EmberJs. Below is the most recent code I have tried: let endpoint = '/api/foo/'; let options = { url: endpoint, type: ...