Utilize a JavaScript function on an element that is generated dynamically

I am encountering an issue with my autocomplete function. It works perfectly fine for the input field with the id "field10" that is already created. However, when I dynamically generate new input fields, the function does not seem to work on them. I have pre-defined the names of these new input fields before creating them and I have verified that the ids are correct. Can someone help me figure out what might be causing this problem? Below is the code snippet used to generate the new input fields.

        //Creating New Input Fields
        $(document).ready(function() {
            var max_fields = 10; //Maximum number of input fields allowed 
            var wrapper    = $(".array_wrap"); //Wrapper for input fields
            var add_button = $(".add_fields"); //Class or ID of the add button
            var x = 1; //Initial input field counter set to 1

         //When user clicks on the add button
         $(add_button).click(function(e){
                e.preventDefault();
         //Check if maximum number of input fields are reached
                if(x < max_fields){ 
                    x++; //Increment input field counter
         //Add a new input field
                    var inputA = document.createElement('a');
                    $(inputA).attr("href", "javascript:void(0);");
                    $(inputA).attr("class","remove_field")
                    inputA.innerText ="Remove";
                    var inputName = document.createElement('input');
                    $(inputName).attr('id','field10' + x);
                    $(inputName).attr('type','text');
                    $(inputName).attr('name','input_array_name[]');

                    $(inputName).attr('placeholder','Subject');
                    $(inputName).appendTo($(wrapper));
                    $(inputA).appendTo($(wrapper));
                }
            });

//
These are the parameters passed to the autocomplete function...
        autocomplete(document.getElementById("field10"), countries);
        autocomplete(document.getElementById("field101"), countries);
        autocomplete(document.getElementById("field102"), countries);
        autocomplete(document.getElementById("field103"), countries);
        autocomplete(document.getElementById("field104"), countries);
        autocomplete(document.getElementById("field105"), countries);
        autocomplete(document.getElementById("field106"), countries);

Answer №1

Do you believe these ids are accurate? If not, considering using classes instead of Ids could be beneficial. When working with a group of elements that share the same class name, it becomes easier to make dynamic changes by looping through the array.

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

The YouTube Iframe API encountered an issue while attempting to send a message to an HTTP recipient. The recipient's origin

Encountering an error when using the YouTube Iframe API on Safari 9.1, OS X Yosemite Issue: Unable to post message to http://www.youtube.com. Recipient has origin https://www.youtube.com This problem only occurs in Safari, as other browsers like Firefo ...

Expanding the capabilities of Prestashop's ajaxCall function to display the content of a tpl file

I'm encountering an issue with extending the ajaxCall function in the blocklayered.php file. $smarty->assign( array( 'myVariable' => 10, 'homeSize' => ..., 'nb_products' => $nb_products, ...

Access information from a service

I have developed a new service named servcises/employees.js: angular.module('dashyAppApp') .service('employees', function () { this.getEmployees = function() { return $.get( '/data/employee.json' ); }; }); ...

Capture any clicks that fall outside of the specified set

I am facing an issue with my navigation drop down menu. Currently, the pure CSS functionality requires users to click the link again to close the sub-menu. What I want is for the sub-menu to close whenever a click occurs outside of it. I attempted a solu ...

What methods does GitHub use to determine my login status?

I removed the localStorage storage, but it didn't make a difference. I'm curious - does GitHub store IP addresses of logged-in users in a database, or maybe in browser headers? ...

Store the information retrieved from an Ajax call regarding an artist on the page, ensuring that it is only saved once for that

I have been working on a single-page application that utilizes the Spotify REST API and JQuery to enable users to search for an artist and display their information on the page. However, I want to ensure that the app saves details about each artist only ...

Guide on attaching an event to every dynamically created element in JavaScript

I'm currently generating 'li' elements dynamically using a loop and running into issues when it comes to assigning events to each generated element. My goal is to assign an onclick event to every li element that is created. Check out the co ...

How can I retrieve an array from the server side using AngularJS?

Currently, I'm involved in developing a web application meant for team collaboration. While the login and signup pages have been set up, other members of my team are focusing on the server (built with node.js and express framework) and database aspect ...

Displaying a random number triggers a snackbar notification in a ReactJS application

Currently, I am utilizing the notistack package to display a snackbar on the screen. However, when calling the Snack component with enqueuesnackbar, a random number is displayed along with the snackbar. I'm looking to eliminate this random number fro ...

What's the best way to set up multiple NestJS providers using information from a JSON file?

Recently diving into NestJS, I am in the process of building an application following the MVC architecture with multiple modules including: Project | +-- App.Controller +-- App.Service +-- App.Module | +-- SubModule1 | | | +-- SubModule1.C ...

Issues with Submitting Ajax Form in Rails 5

My goal is to send this form using ajax. <%= form_tag contact_form_submission_path, remote: true do %> <div class="row"> <div class="col-md-4"> <div class="form-group"> <%= tex ...

a guide on configuring a default input value from a database in a React component

In my current project, I have an input field with the type of "checkout" and I am looking to utilize Firestore to retrieve a default value. Once I obtain this value, I plan to store it in the state so that it can be modified and updated as needed. Here i ...

Guide to Implementing the GitHub Fetch API Polyfill

I'm facing an issue with making my code compatible with Safari by using the GitHub Fetch Polyfill for fetch(). I followed the documentation and installed it using: $ npm install whatwg-fetch --save Although I completed this step, I am unsure of how ...

Find the string "s" within a div element aligned vertically, using Popper

Currently utilizing Popper from Material-UI <Popper id={"simplePopper"} open={true} style={{backgroundColor: 'red',opacity:'0.5',width:'100%',height:'100%'}}> <div style={{height:"100%", ...

While attempting to use JavaScript and AJAX to read a JSON object, I encountered an issue caused by the CORS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Docu ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

Getting a list of connected users on a PeerJS server using Express is simple and straightforward. Follow these steps to

Trying to incorporate PeerJS, a webRTC library, into a game and utilizing their server for user discovery has proven challenging. The goal is to manage a list of connected users, but grappling with the PeerJS server has been difficult. The documentation s ...

Semantic UI (React): Transforming vertical menu into horizontal layout for mobile responsiveness

I have implemented a vertical menu using Semantic UI React. Here is the structure of my menu: <Grid> <Grid.Column mobile={16} tablet={5} computer={5}> <div className='ui secondary pointing menu vertical compact inherit&apos ...

The jQuery function .val()/.text() is unable to retrieve information from a particular section of HTML

Implementing HandlebarsJS with PHP and Yii to generate a page. Here is a snippet of the html/handlebars code on the page {{#if embed_link}} <p class='f_hidden_p'> <a href='{{embed_link}}'> {{ ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...