The jquery autocomplete feature is failing to function properly when applied to input boxes that are

Currently, I am experimenting with adding jQuery autocomplete functionality to all input boxes on a web page. Initially, there are only two input boxes, but users can dynamically add more. The autocomplete feature works fine in the first two boxes but fails in the dynamically added ones.

You can check out the code in action here: http://jsfiddle.net/HG2hP/

Here is the code snippet:

HTML:

<!doctype html>
<html>

    <head>
        <title>TakeMeHome</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
         <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
         <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>
         <script type="text/javascript" src="js/app.js"></script>
         <link type="text/css" rel="stylesheet" href="css/design.css"/> 

    </head>

    <body>
        <center>
                Your Place:<input class="address" id="source" type="text"/><br/>
                <div id= "div1">Friend1:<input class="address" id="friend1" type="text"/></div><br/>
                <pre>
                <div id="button">Add!</div> <div id="button2">Remove</div></br>
            </pre>
            <div id="sumbit_button">GO!</div>
            <div id="map" style = "width: 500px; height: 500px"></div>

        </center>

    </body>

</html>

JavaScript (JS):

$(document).ready(function() {

var geocoder;
var map;
var marker;
var friends_cnt = 1;
var friends = [];
var distance = [];

$('#button').click(function() {
    if (friends_cnt < 11) {
        $('<div  id = div' + (friends_cnt + 1) + '>Friend' + (friends_cnt + 1) + ':<input type="text" class="address"  id="friend' + (friends_cnt + 1) + '"/></div>').insertAfter('#div' + friends_cnt);
        friends_cnt++;
    } else {
        console.log("Limit reached");
    }
});

// Code for removing buttons omitted for brevity

geocoder = new google.maps.Geocoder();

$(function() {
    $(".address").autocomplete({
        source : function(request, response) {
            geocoder.geocode({
                'address' : request.term
            }, function(results, status) {
                response($.map(results, function(item) {
                    return {
                        label : item.formatted_address,
                        value : item.formatted_address,
                        latitude : item.geometry.location.lat(),
                        longitude : item.geometry.location.lng()
                    }
                }));
            })
        },
    });
});

$('#sumbit_button').on("click", function() {
    console.log("button clicked");
    var a = [];
    a.push($("#source").val());
    for ( i = 1; i <= friends_cnt; i++) {
        a.push($("#friend" + i).val());
    }

    // AJAX call and processing of response data omitted for brevity
});

CSS:

input {
margin: 10px 4px;
}

#button, #button2 {

    width: 70%;
    margin: 0 auto;
}

.ui-autocomplete {
    background-color: white;
    width: 300px;
    border: 1px solid #cfcfcf;
    list-style-type: none;
    padding-left: 0px;
}

.ui-helper-hidden-accessible {
    display: none;
}

If you spot any errors or have suggestions on how to improve the implementation of the autocomplete feature using classes, please let me know.

Answer №1

When handling your click event:

$('#button').click(function ()...

Make sure to apply the autocomplete to any new input fields that are added dynamically, like this:

    $('#button').click(function () {
        if (friends_cnt < 11) {

        $('<div  id = div'+(friends_cnt+1)+'>Friend' + (friends_cnt+1) + ':<input type="text" class="address"  id="friend' + (friends_cnt+1) + '"/></div>').insertAfter('#div'+friends_cnt);

       $('div#div'+(friends_cnt+1)).autocomplete(...);

       friends_cnt++;

    }

    else {
        console.log("Limit has been reached");
    }

});

This is important because the autocomplete only works on elements currently in the DOM, not ones added dynamically.

Answer №2

If you follow Kapo's advice, you should reapply the auto complete to each element individually.

 $('div#div'+(friends_cnt+1)).autocomplete(...);

Alternatively, you could utilize liveuery (refer to this thread for more information).

Answer №3

When the page loads, the autocomplete feature is set to fields labeled with the class .address. However, since there are no .address fields on the page during this time, the autocomplete function does not attach to anything.

To fix this issue, you should execute the following code:

$(".address").autocomplete({

Immediately after adding a new field to the document or, even better, convert the input into an object. By doing so, you can directly apply events to it like so:

$input = $('input')
            .attr('type', 'text')
            .attr('class', 'address')
            .attr('id', 'friend')
            .autocomplete({ etc

Answer №4

After receiving the solutions, I found that this modification in the code was effective: Inserting the following within the $('#button').click(function () { block

$(function() {
   $("#friend"+(friends_cnt+1)).autocomplete({
      source: function(request, response) {  . .. . . 

By doing this, autocomplete functionality will be applied to all boxes created.

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

Enhancing the appearance of div content in Angular by utilizing local template variables and material elements

Within this particular implementation, I have utilized an md-sidenav component with a local template variable #sidenavsearchArea. <md-sidenav #sidenavSearchArea align="" mode="push" opened="false"> sidenav content here.. </md-siden ...

What sets apart genuine user interactions from programmatically generated actions?

Working with webkit notifications on Chrome has presented a challenge. The window.webkitNotifications.requestPermission method must be called from a user action, such as a click. Attempting to call it at any other time will not have any effect and will not ...

ng-click - triggers a function and then redirects to another page

I'm facing a small issue. I am trying to set up an ng-click event that redirects, but before the redirect happens, I need to send some data through post request. Here is my HTML code : <a href="/test" ng-click="updateData($event)">Go</a> ...

What is the best way to modify a current state object without causing an endless loop of redirects?

const useCase = (argument) => { const [value, setValue] React.useState(argument) React.useEffect(() => setValue({...value ...argument), [argument, value, setValue]) } The above code is currently causing an infinite loop due to setting the stat ...

Getting data with a data attribute - a step-by-step guide

I'm attempting to retrieve data from our API using a unique html method involving the data- attribute. I am able to successfully fetch the data directly and load it without any issues. However, when trying to access the data variable from the data att ...

Creating a Prismoid Shape Using Three.js

Currently, I am utilizing Three.js and my objective is to construct a pyramid shape with its apex removed. The base of the pyramid should be a rectangle instead of a square, while the top should also be a rectangle, but not in equal proportions. Here is a ...

The synopsis cannot be displayed by the RottenTomatoes API

I'm having some trouble with the RottenTomatoes movies API. I've been trying to display the movie's synopsis below the input field, but it's not working as expected. Can anyone point out what might be causing the issue here? If you nee ...

What is the best way to save a chosen item from a jQuery autocomplete dropdown?

I have been working on creating a small web application where users can search for games using the Giantbomb API. The idea is that once they select a game from the list, it will be added to a top 10 list that can later be sorted. Although I managed to get ...

Recording setInterval data in the console will display each number leading up to the current count

Currently, I am developing a progress bar that updates based on a counter over time. To achieve this, I opted to utilize a setInterval function which would update the counter every second, subsequently updating the progress bar. However, I encountered an ...

Ensure accurate interpretation of CSS3 transform percentages on Android devices

tl;dr? Looking for a way to enable GPU acceleration on Android Chrome & default browser for the mechanism shown in the link below. UPDATE 2 (2014-01-13 13:25:30Z): As per bref.it's comment, the issue was resolved with Android 4.4 KitKat but my previo ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...

A guide on integrating Select2.js with WebForms

I am looking to make the switch from Ext.net to select2 js, but I'm struggling with integrating scripts and controls. So far, I have started a new WebForms App, installed select2 through NuGet, and attempted to replicate a sample from the Project sit ...

Symfony action encountering difficulty in fetching correct AJAX JSON information

I'm attempting to send a JSON object to a Symfony action. The code used to create and send the array is shown below: var rows, arr = []; rows = table.find('table tbody tr'); arr['x'] = new Array(rows.length); table ...

The issue of the selection option not being cleared after being set to 0 persists in JavaScript

I am facing an issue where I need to reset the select option to `0` when another option is selected. I have tried the code below for this purpose. if (varALPO1MobNum == "0") { var selectElement = $(&apo ...

Unusual behavior observed with AngularJS checkboxes

Our group of friends is collaborating on a new project. This is my second time working with AngularJS, and we're currently utilizing version 1.2.3. Although I have some experience, there are moments when I find AngularJS's behavior perplexing, a ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

How can I incorporate a .shtml file into a .php webpage?

Is there a way to include a .shtml file within a .php page? I know it can be done, as I have successfully achieved this in the past (although I cannot remember the exact code). Can someone please assist me with this? ...

Error message: Unexpected token "(" in the asynchronous aspect of Meteor

Currently running meteor version 1.5.1, I am facing a bug while attempting to import an npm module (kraken-api) on the server side: import KrakenClient from 'kraken-api'; > W20170726-22:02:48.177(2)? (STDERR) packages/modules.js:677 ...

Ways to troubleshoot the MudTabPanel during scrolling

I am trying to create a fixed text at the top of a scrollable MudTab. As I scroll down, I want the text to remain visible. Here is an example of what I have done: <MudTabs Position="Position.Top" PanelClass="pt-2" Style="hei ...

Enhancing Material UI KeyboardDatePicker with personalized CSS design

Material UI KeyboardDatePicker is the component I'm currently using. https://i.sstatic.net/It50L.png In order to remove the black line visible in the datepicker (as shown in the screenshot), what steps should I take? Displayed below is the code ...