yourlabs/django-autocomplete-light

Cloning an autocomplete form dynamically

YasirKusay opened this issue · 8 comments

Hello,

I am sorry for opening up an issue for this but I did not know where else to ask this.

Lets say I have this form:

class PostForm:
    tag = forms.ModelChoiceField(queryset=Tags.objects.all(), 
                                                  required=True, 
                                                  widget=autocomplete.ModelSelect2(url='tag_autocomplete', 'attrs': {'id: 'tag_1'}}))

In otherwords, it contains an autocomplete field that calls tag_autocomplete to fetch a possible list of results from the search. (In the actual form, there are more fields but I am trying to keep the code as simple as possible)

I also have a view that takes the above form and renders it in a html file like this:

<form>
    {{ post_form.tag }}
    <input type="submit">
<form>

How can I create a duplicate of the autocomplete field, for example, by clicking an “Add Additional Tag” button. Normally, you can just get a duplicate of an input element by cloning it and changing the new one’s ID/name before appending it to the html. However, this is not possible here as DAL does some additional rendering which adds additonal tags below the form element (I tried to understand how it works from the documentation, specifically the tutorial but I couldn’t).

jpic commented

I prefer to keep separate autocomplete forms, rather than using a single autocomplete form. Is there another way?

jpic commented

Sorry, I meant that I would like separate autocomplete fields.

jpic commented

I tried that before creating this issue, but there were a few problems with this. I made a simple recreation of what I was originally trying to achieve:

I have an all_autocomplete_forms div that stores wrapperDiv divs that actually contains the autocomplete form. When you click the add_more button, it will duplicate an the individual element (via cloneNode), change attributes such as the name and id and insert it into a new wrapperDiv which in turn gets inserted back into all_autocomplete_forms. Please look at the output attached here:

error1 In the above error, I am highlighting the div containing the first autocomplete element (which is missing the span element). error2

In the second image, I am highlighting the div the div containing the second autocomplete element. This, along with any subsequent elements appears fine.

I also did a method where I cloned the entire wrapperDiv element itself and changed attributes inside it before inserting it back into all_autocomplete_forms. The results of this are identical.

Could you let me know if I can do anything differently?

Hi I just want to check in again. Could you let me know if I did anything wrong and if I can do anything differently?