Your Location is: Home > Javascript

How to clone and append a child inside a “for-function” - pure javascript

From: Fidschi View: 2440 Blazej Meisner 


here at work our helpdesk-members have to write a lot of support tickets and send them via Mail to the IT. It takes a lot of time, because the common way to do the task is to search for an already send ticket and to rewrite it by hand. Although I'm fairly new to javascript, I managed to write a so called "ticket-generator". It contains the input fields, stores the input in localstorage and generates at the end the complete text, inserts it in an outlook mail-body and we are ready to hit the "send" button within seconds.

My problem now: I'd like to let people choose how many predefined input-fields they need, if they want to write multiple tickets at once.

This is where I'm stuck:

The html:

       <form id="ticketform">
                <input id="projectselection" name="projectselection1" list="projects" placeholder="Choose project...">
                    <datalist id="projects">
                        <option value="Project1"></option>
                        <option value="Project2"></option>
                        <option value="Project3"></option>
                <input id="numberoftickets" type="number" placeholder=" Choose the number of tickets...">
            <button id="newForm" onclick="newnew()">DO IT!</button>
            <div id="dynamicInput">

The script:

function newnew() {
    let inputNumberoftickets = document.getElementById("numberoftickets").value;
    localStorage.setItem("selectionNumberoftickets", inputNumberoftickets);
    let original = document.getElementById("projectselection");
    let clone = original.cloneNode(true);
    let y = inputNumberoftickets;
    let formform = document.getElementById("ticketformular");
    let text = "";
        for (i = 1; i <= y; i++) {
            document.getElementById("dynamicInput").innerHTML = text += 'Ticket ' + i + "<br>" + 
            original.setAttribute("id", ticketformular + i) +
            document.getElementById("dynamicInput").appendChild(clone) + "<br>";

This is the result i get:

Ticket 1
undefined[object HTMLInputElement]
Ticket 2
undefined[object HTMLInputElement]
Ticket 3
undefined[object HTMLInputElement]

Did a lot of research but somehow I'm complete stuck. Even when I set the project input in local storage to define the field i got no output.

Thanks in advance. Wish you a nice day.

Best answer