Guide on duplicating a Select2 element integrated with Django and Python

I am facing an issue where the select element inside a div is not cloning correctly. The Select2 element does not retain the loaded values from the Django code when cloned. Is there a way to clone the div with all the Select2 element values intact? Currently, when I clone, it duplicates but the selects do not display the values. Thank you for your assistance.

<script>
counter = 0
function addTopic(){
  $( "#select" ).clone().appendTo( "#trying" );
}
</script>
</head>
<body>
<button onclick="addTopic()">Add Topic</button>

<form action="{% url 'testing_show' %}">
<div id="trying">
    <div id="select">
        <select class="js-example-basic-multiple" multiple="multiple">
        {% for taf_doc in taf_documents %}
            <option value="{{ taf_doc.id }}">{{ taf_doc.taf.nom }}</option>
        {% endfor %}

        </select>

        <select class="js-example-basic-multiple" multiple="multiple">
        {% for ue_doc in ue_documents %}
            <option value="{{ ue_doc.id }}">{{ ue_doc.ue.nom}}</option>
        {% endfor %}

This is the header :

<head>
<meta charset="UTF-8">
<title>Title</title>
<script 

src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(document).ready(function(){
  $(".js-example-basic-multiple").select2();
});//document ready
</script>

Answer №1

For those who are visiting this page, I initially had to 'eliminate' the existing select2

$("#parentDiv").children("select").djangoSelect2("destroy")

I then duplicated the div, incremented the ids, and removed the select2-container that was nested within the original select2 select element (to prevent duplicates when re-initializing select2)

let form_count = 1

function cloneAndChangeIds(wrapper) {

          // duplicate the wrapper
          let clone = wrapper.cloneNode(true);
          clone.id ="form_" + form_count;

          // update the `for` attribute of every label
          const labels = Array.from(clone.querySelectorAll('label'));
          labels.forEach(label => {
            label.htmlFor += "_" + form_count;
          });

          // modify the `id` attribute of every select and input
          const items = Array.from(clone.querySelectorAll('select, input'));
          items.forEach(select => {
              select.id += "_" + form_count
              if(select.hasAttribute('data-select2-id')){
                  select.setAttribute('data-select2-id', select.id)
              }
          });

          const s2items = Array.from(clone.querySelectorAll('.select2-container'));
          s2items.forEach(select => {
              select.remove()
          });
          return clone;
        }

const container = document.getElementById('parentDiv');
const original_form = document.getElementById('original_form');

and lastly, I appended it back to the parentDiv and re-initialized the djangoSelect2 on both select2 elements

addForm = () => {
            form_count = form_count + 1
$("#original_form").children("select").djangoSelect2("destroy")
            const clone = cloneAndChangeIds(original_form)
            container.appendChild(clone);
            $("#id_segment_"+ form_count).djangoSelect2();
            $("#parentDiv").children("select").djangoSelect2();
}

Sorry for my not-so-great javascript code styling

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

Utilizing the real module instead of resorting to mock usage

I've configured Jest as follows: jest: { configure: { testEnvironment: 'jsdom', preset: 'ts-jest', transform: {...}, moduleNameMapper: { antd: '<rootDir>/__mocks__/antd/index.tsx&apo ...

Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue. To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following st ...

How to delete a line from a file in Node.js without modifying the buffer variable

Hello everyone, I am just starting to explore the world of Nodejs Recently, I created a function that reads data from a file, saves it in an array variable, and then makes some changes to this variable before writing it back to the file. The code snippet ...

What could be the reason for this code returning a "module not found" error?

Within localbase.js... const fs = require("fs"); if(!fs.existsSync(__dirname + "/localbase.json")) fs.writeFileSync("./localbase.json", "{}"); let database = require("./localbase.json"); The code abov ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

Determine if a JSON object is void

Using jQuery, I am checking whether the object returned from an AJAX call is empty or not. In the first example, the AJAX call is successful and returns some data. console.log("obj before JSON parse:", response); var test = $.isEmptyObject(response); con ...

Navigating through JSON Serialization in Django and Unpacking JSON Data in Jquery

So here's the code snippet that I'm currently working with: def success_comment_post(request): if "c" in request.GET: c_id = request.GET["c"] comment = Comment.objects.get(pk=c_id) model = serializers.serialize("json" ...

How to securely upload and generate a permanent link for the contents of a zip file using express js

I am new to Javascript and Node JS. I have a challenge of uploading a zip file containing only pictures and creating permanent links for these pictures. Currently, I can upload a zip file and extract its contents using the following code snippet: var expr ...

Why is the model so tiny after converting my FBX file to a .gltf format?

QUERY: I am facing an issue where my model appears extremely small after converting the FBX file to a .gltf format. Despite attempting to scale the model using frontObject.scale.set(1000, 1000, 1000);, I encounter the following error: TypeError: Cannot r ...

How can the entire menu be closed in Bootstrap 5 when clicking on a link or outside of the page?

I'm currently utilizing BootStrap 5 for constructing my webpage. Within my page, I have a NavBar Menu containing various links. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Django ModelForm encountering issues with subclassed models: Error arises for one model but not for another (Error message: 'NoneType' object does not have attribute 'label')

I need some guidance regarding a django issue: These are the models I am currently using: class QItem(models.Model): isWhat = models.CharField(max_length=100, blank=True, choices=ISWHAT) slug = models.SlugField(blank=True) script = models.Ch ...

Node.js server experiencing delays due to V8 processing constraints

REVISED I am currently running a nodeJS http server designed to handle uploads from multiple clients and process them separately. However, I have encountered an issue where the first request seems to block any subsequent requests until the first one is co ...

Typing text into an input field by tapping on a picture

Is there a way to create a feature where users can browse and insert images, which will pull the image URL (all image information is stored in a database) into an input field for submission? Similar to how WordPress allows you to browse, select an image, ...

Having trouble triggering drag events efficiently with d3-drag on SVG elements

drawAll refers to a two-dimensional array where each drawAll[i] element represents a drawing containing all the strokes. A stroke is essentially a string representing a series of 2D points that can be utilized to generate a <path>. I am currently at ...

What is the most effective method for locating and modifying the initial instance of an element within a group?

In my Javascript/Typescript collection, I have the following items: [ {"order":1,"step":"abc:","status":true}, {"order":2,"step":"xyz","status":true}, {"order":3,"step":"dec","status":false}, {"order":4,"step":"pqr","status":false}, {"order":5,"step":" ...

Is it advisable to consolidate all of my JavaScript files into a single file?

Is it necessary for me to combine all my JavaScript files into one single file and then include that file in a folder? I currently have 10 separate JS files within a "javascript" folder - is this bad for the website, or is it okay? P.S. I am new to web de ...

Excessive JSON formatting is consuming an excessive amount of storage space

As I work on developing a website that recommends locations to visit in NYC, I am facing an issue with saving JSON data in local storage. My goal is to allow users to add their own suggestions and eventually integrate MongoDB into the site. To build the si ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

There appears to be some lingering content in the JQuery Mobile slide-out dialog box

My jQuery mobile slide out dialog box is experiencing an issue. The first time the slide out occurs, a comment box appears where users can enter comments and then submit them, followed by a "THANK YOU" message. However, when the user closes the dialog box ...