Search code examples
javascripthtmldomappendchild

keeping values after adding an appendchild


I have a problem... this is my code

 <script lenguaje="javascript">
        var cont = 1;

        function add() {
            if (cont != 11) {
                var textoagregar = document.createTextNode("Agregar alternativas");
                var espacio = document.createElement("br"); 
                var element = document.createElement("input");

                element.setAttribute("type", "text"); 
                element.setAttribute("name", "preguntas[]");
                element.setAttribute("id", "id" + cont);
                var foo = document.getElementById("fooBar");
                foo.appendChild(element);
                foo.innerHTML += "<input type='button' value='+' onclick='agregaralternativa(" + cont + ")'><input type='button' value='-' onclick='removeralternativa(" + cont + ")'><div id='" + cont + "'></div>";
        foo.appendChild(espacio);
        cont++;
            }

        }

        function remover() {
            if (cont > 1) {
                cont--;
                var foo = document.getElementById("fooBar");
                var child = document.getElementById("id" + cont);
                foo.removeChild(child);
                var lChild = foo.lastElementChild;
                foo.removeChild(lChild);
                var lChild = foo.lastElementChild;
                foo.removeChild(lChild);
                var lChild = foo.lastElementChild;
                foo.removeChild(lChild);
                var lChild = foo.lastElementChild;
                foo.removeChild(lChild);
            }

        }

        function agregaralternativa(id) {


            var panel = document.getElementById(id);

            panel.innerHTML += "<input type='text value='alternativa" + id + "[]'><br>";

        }

        function removeralternativa(id) {


            var panel = document.getElementById(id);

            var lChild = panel.lastElementChild;
            panel.removeChild(lChild);
            var lChild = panel.lastElementChild;
            panel.removeChild(lChild);

        }
        </script>

        <div class="form-group">
            <label class="col-md-4 control-label">Ingrese preguntas</label>
            <div class="col-md-6">  <span id="fooBar"></span>   
                <INPUT type="button" value="Remover" onclick="remover()" />
                <INPUT type="button" value="Agregar" onclick="add()" />
            </div>
        </div>

and every time that you add a text field with the buttons + or "agregar pregunta" all the other values disappear, how can i add text fields without lossing the existent fields values?


Solution

  • You destroy elements previously created when you do this:

    panel.innerHTML += "...";
    

    Instead use insertAdjacentHMTL() if you want to append using HTML markup.

    panel.insertAdjacentHTML("beforeend", "...");
    

    Now instead of going through this destructive process...

    1. serialize the existing DOM nodes to HTML
    2. concatenate the new HTML fragment to the serialized nodes
    3. destroy the old nodes
    4. recreate the nodes with the new nodes

    ...it simply creates the new content and places it before the close of the body element.

    Basically, remove element.innerHTML += ... from your coding practices. It's never necessary, it's inefficient and it causes problems like what you've described.


    FYI, the .insertAdjacentHTML() method receives 4 different string possibilities as the first argument. Each one designates a position relative to the element on which you're calling it.

    The strings are...

    • "beforebegin"
    • "afterbegin"
    • "beforeend"
    • "afterend"

    The labels are pretty self-explanatory. They position the new content before the current element, inside the current element at the beginning, inside the current element at the end, or after the current element, respectively.