Binding autocomplete to a dynamically added form field

Go To StackoverFlow.com

0

I'm trying to bind the jQuery UI autocomplete widget to a dynamically added input field. I've read some of the posts here, but none seem to help.

The code I'm using comes from Dynamically adding a form to a Django formset with Ajax and I've slightly modified it to bind the autocomplete.

However, the bind doesn't seem to be working. Whenever I type in the newly added field, the autocomplete box doesn't show. The code I am using follows:

function cloneMore(selector, type,field) {
    var newElement = $(selector).clone(true);
    var total = $('#id_' + type + '-TOTAL_FORMS').val();
    newElement.find(':input').each(function() {
        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
        var id = 'id_' + name;

        if ($(this).attr('type') != 'hidden') {
            $(this).val('');
        }
        $(this).attr({'name': name, 'id': id}).removeAttr('checked');
    });
    newElement.find('label').each(function() {
        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
        $(this).attr('for', newFor);
    });
    total++;
    $('#id_' + type + '-TOTAL_FORMS').val(total);
    $(selector).after(newElement);

    /* create the selector string and bind autocomplete */
    var select_string = "#id_"+type+"-"+(total-1)+"-"+field;
    $( select_string).autocomplete({
        source: asset_universe_codes,
    });

}

I have checked that the autocomplete source is accessible within the function, so I'm at a loss.

Can anyone help?

Thanks,

Jason

2012-04-05 22:57
by xyzjace
Have you tried .on() and delegate() - Chibuzo 2012-04-05 23:04
I haven't, no. I'm relatively new to jQuery, so I wasn't aware of those methods. Delegate looks like it might be promising, thanks - xyzjace 2012-04-05 23:09


1

It would appear that newElement hasn't been appended to the DOM, if this is the case then appending it (prior to calling autocomplete) should resolve your issue.

2012-04-05 23:05
by Marc Gagne
Ah, I see. I was under the impression that 'after' did that for me. I'll look up how to append and give that a go, thanks - xyzjace 2012-04-05 23:11
Would it be possible to get an example of this, please? I struggled to find an answer - xyzjace 2012-04-12 00:41
Ads