Replicate and $(document).ready()

My form has required fields that need to be completed. To alert users about blank fields, I have implemented the following code:

$(document).ready(function() {
    $('input.required:text').focus(function() {
        $(this).css({'background-color': '#FFF'});
    });
    $('input.required:text').blur(function() {
        if ($(this).val() == '') {
            $(this).css({'background-color': 'rgba(222, 41, 30, 1)'});
        }
    });
})

The issue arises when I use an "add" button to duplicate a hidden form using this function:

function addlocation() {
    var clone = $('div.location-info-new').clone();
    clone.addClass('location-info');
    clone.find('form').addClass('ready');
    clone.removeClass('location-info-new');
    clone.appendTo('div.locations');
    clone.find('input.required:text').focus(function() {
        $(this).css({'background-color': '#FFF'});
    });
    clone.find('input.required').each(function (i, v) {
        $(this).css({'background-color': 'rgba(222, 41, 30, 1)'});
    });
}

To address this issue, I included background-color changes in the cloned form as they were not working initially. However, there is still a problem. The new form's fields correctly display in red initially and change to white upon focus. But, if a user focuses on an input box, leaves it empty, and removes focus, the input box does not revert back to red. This behavior is different from the original form where it works properly.

I am puzzled as to why the background-color changes from document.ready are not being applied to my cloned form. Can anyone shed light on this issue?

Answer №1

As new elements are dynamically added after subscribing to existing ones, you can utilize the jQuery on function to subscribe to both the initial form elements and any future ones.

$(document).ready(function() {
    $(document).on('focus', 'input.required:text', function() {
        $(this).css({'background-color': '#FFF'});
    });
    $(document).on('blur','input.required:text', (function() {
        if ($(this).val() == '') {
            $(this).css({'background-color': 'rgba(222, 41, 30, 1)'});
        }
    });
})

Answer №2

How come the background-color changes I applied during document.ready aren't showing up on my cloned form?

The reason is that the newly cloned elements do not have the event handler attached to them. You have bound the focus event handler like this:

clone.find('input.required:text').focus(function() {
    $(this).css({'background-color': '#FFF'});
});

However, you have not bound the blur event handler. There are a few ways to address this issue:

Manually attach the blur event handler

Simply add

clone.find('input.required:text').blur(function() {
    if ($(this).val() == '') {
        $(this).css({'background-color': 'rgba(222, 41, 30, 1)'});
    }
});

to your function.

Use .clone correctly

Upon reviewing the documentation, you'll find that .clone accepts a boolean argument that allows for copying data and event handlers. So, you can use

var clone = $('div.location-info-new').clone(true);

instead and eliminate

clone.find('input.required:text').focus(function() { ... });

Utilize event delegation

This concept is well explained in the jQuery tutorial: https://learn.jquery.com/events/event-delegation/

Answer №3

It is not possible to directly trigger the event on a programmatically added element.

Instead, you can use the on method to bind a function to your element.

Modify your code like this :

$(document).ready(function() {
    $('input.required:text').on("focus", function() {
        $(this).css({'background-color': '#FFF'});
    });
    $('input.required:text').on("blur", function() {
        if ($(this).val() == '') {
            $(this).css({'background-color': 'rgba(222, 41, 30, 1)'});
        }
    });
})

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

What is the best way to display a scrollbar at the bottom of the table while setting the table height to

After writing the css provided below, I noticed that it works fine on my laptop screen. However, when viewing it on a larger monitor, there is empty space at the end of the table. .wrapper{ width:auto; height: 500px; overflow-x: scroll; ...

I'm looking for the specific jQuery/JavaScript function that will accomplish this task

let data = [{ name: "abcd", type: "1 kg" }, { name: "efgh", type: "1 cai" }, { name: "ijkl", type: "1 kg" }]; If I have the name, I would like to get the corresponding type. For example, if I call getType('abcd'), it sho ...

Target specifically the onhover div element using JQuery and trigger the smooth sliding down effect with the SlideDown() function

Is it possible to create a unique JQuery slidedown() function that will only be applied to the div where the mouse is hovering? I have managed to make it work by giving each div a separate class, but when I name them all the same, it triggers the slide do ...

Positioning a Three.js static CSS2DObject with respect to the camera's perspective

I am currently working on a unique program visualizer that utilizes Three.js to showcase various aspects of a program to the user. One crucial feature of this visualizer is allowing users to click on specific objects to view additional information about th ...

What is the best way to iterate through .next()?

I currently have 3 divs all with the same class. When I click on one, it adds the class 'selected' to the next div and removes it from the previous div. Everything is working fine, but now I want this process to loop. Right now, the order goes f ...

Issue with border-color in CSS on Chrome tables

Here is a table style I have defined for selected elements: tr[selected] { background: #FFF; border-color: #000000; color: #000000; } To apply this style, I use JavaScript: $this.unbind().change(function () { element = $(this).parent ...

Guide on utilizing Vercel KV for storing and fetching posts from an API

Looking to optimize your API by utilizing Vercel KV for storing and retrieving posts? If you have a basic node.js express API that pulls random posts from MongoDB, the process of integrating Vercel KV can enhance performance. Initially, the API will resp ...

Determining Field of View (FOV) for a perspective camera in ThreeJS following a browser window resize

After changing the size of the browser window, I'm trying to determine the correct Three.JS camera FOV. I have looked at several related questions, but haven't found a solution yet: How to calculate fov for the Perspective camera in three js? C ...

Does Vuejs emit an event when a specific tab becomes active in boostrap-vue?

I am looking for a way to display and hide a section on my page when a specific tab is active, and close it when the tab is inactive. I have tried using the forceOpenSettings and forceCloseSettings methods for opening and closing the div. Is there an event ...

Ways to maximize the amount of content contained within a box

My current struggle involves meeting the requirements of my customers. I have a small box (230px x 200px) with an image that will display a list on hover. However, the customer now wants more items in the list than can fit in the box. Scrolling within the ...

Having difficulties with Smooth Div Scroll and Colorbox integration

Check out the gallery page by following this link: http://www.gerardtonti.com/Scrollable%20Gallery%2/index.html After trying numerous methods, I am still facing the same issue. Upon discovering your jQuery Smooth Div Scroll tool online, I intend to contr ...

Issues arise when attempting to transfer strings through ajax to a Node.js server that is utilizing express.js

On my website, I am encountering a problem where certain characters are being lost when I send strings to my Node.js server. // Client: microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){}); // Server: app.get('/foo',fun ...

Tips on interpreting JSON objects and cross-referencing them with user input

I am currently developing an application where specific values are stored in JSON format and I aim to access these values through indexes rather than hard coding them. Below is a snippet of my HTML file combined with JavaScript: <html> <head> ...

Is there a way to resolve the execution order dependency of JS-CF using a server-side callback function?

Is there a way to display a form as a pop-up window, with input fields and a submit button, and then retrieve the user's selection from the session? The challenge lies in integrating JS code for the pop-up window with CF server-side code, leading to t ...

What methods are available to incorporate arithmetic when defining a style attribute?

Is there a way to achieve arithmetic operations in CSS, like calculating margin-left: -60px + 50% of the width of the parent div? I'm eager to find a solution, whether it involves JavaScript or any other method. Any help would be greatly appreciated. ...

What is the best way to execute the .playVideo() function in Youtube using jQuery?

Is it possible to embed a YouTube video and have it play immediately upon clicking using jQuery? I'm having trouble figuring out how to implement this with the live click function. Any suggestions? var youTubeVideo = '<object width="370" heig ...

Delving into the intricacies of reactivity within datasets

Seeking assistance with a component issue I am facing. I have a situation where I need to pass a prop and assign a variable from my data to that prop, but it needs to be done in a reactive manner. The child component only accepts Booleans so I cannot modif ...

How can we efficiently loop through all the icons in React Material-UI?

I am looking to iterate over all the icons from @material-ui/icons in a React application. If I want to import a single icon, I can do so like this import IconNameIcon from '@material-ui/icons/IconName' and then use it in my component like th ...

Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive. The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property se ...

Chart rendering failure: unable to obtain context from the provided item

I am encountering an issue while trying to incorporate a chart from the charts.js library into my Vue.js and Vuetify application. The error message that keeps popping up is: Failed to create chart: can't acquire context from the given item Even af ...