0

I have an input text with id school_name field that I would like to apply jQuery autocomplete on. I managed to make it work making an ajax call and fetch the data and show them as options but autocomplete does not work on cloned input text fields although I am using on() to bind. How I could make it work?

See my jQuery code below:

$(document).on('keydown.autocomplete,focus,click', "#school_name,input[name='school_name']", function (event) {
    var getData = function (request, response) {
        $.getJSON(
            "https://api.apispreadsheets.com/data/JIbRHVPsNwrMkmav/?dataFormat=column&query=select Sxoleio,Moria from JIbRHVPsNwrMkmav where MM_ID = " + request.term,
            function ( data ) {
                response( data['Sxoleio'] );
            });
    };
    
    var selectItem = $(document).on('autocompleteselect', "#school_name", function (event, ui) {
        // event.preventDefault();
        $(event.target).val(ui.item.value);
        return false;
    });
    
    var changeItem = $(document).on('autocompletechange', "#school_name", function (event, ui) {
        // $(this).val("").css("display", 2);
        $(event.target).closest('.school').find('#school_points').val(7);
    });
 
    $(event.target).autocomplete({
        source: getData,
        select: selectItem,
        minLength: 3,
        delay: 250,
        change: changeItem
    });
});
$("#school_name").autocomplete('enable');

I tried on() event binder. I tried $(this). Tried $(event.target) or even $(event.target).closest("parent selector").find("specific selector") but it only worked for the first one.

2
  • 2
    Adding event handlers to elements inside another event handler is going to cause you problems. You should only add the event handler once per element. Commented Aug 28, 2024 at 19:27
  • 1
    The whole point of using event delegation is that you don't need to do it each time you create an element dynamically. You need to call .autocomplete() in the code that creates the new element, not here.
    – Barmar
    Commented Aug 28, 2024 at 19:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.