Dynamically generated form field loses value when new field is added – vanilla javascript

I am generating a dynamic fieldset with javascript. For adding fields, I use the following function (this function actually adds more than one field)

//add test

function addTest() {
    var location = document.getElementById('addTestLocation');
    var num = document.getElementById('addTestCount');
    var newnum = (document.getElementById('addTestCount').value -1)+ 2;
    num.value = newnum;

    location.innerHTML += "<div id='testContainer_"+newnum+"'><label for='test_"+newnum+"'>Test name: </label><input type='text' name='test_"+newnum+"' id='test_"+newnum+"'/>&nbsp;&nbsp;&nbsp;<a href='javascript: removeTest("+newnum+")'>- Remove test</a><br/><br/><span id='addObjectLocation'></span><br/><select id='select_"+newnum+"'><option>True or False</option><option>Single choice</option><option>Multiple choice</option><option>Short definition</option><option>Fill in the blanks</option></select><input type='hidden' id='addObjectCount' value='0'/>&nbsp;&nbsp;&nbsp;<a href='javascript:addObject();'>+ add question</a><br/><br/><hr/><br/></div>";
}

I use innerHTML instead of append because there is a lot of code i’d have to append, the markup is so much shorter this way.

Now, my problem is that whenever I add (or remove) a field, all the data from the other dynamically generated data would be lost. How can I fix this? Saving the value and then adding it to every field would be again, very complicated in my case. Any ideas?

Solution:

var any_html = ‘<div><input type=”text”></div>’;

document.getElementById(‘add_row_here’).insertAdjacentHTML(“beforebegin”, any_html);

preserve the dynamic input tag if validation error occur?

Create Dynamically Growing Form – Queries and Resources

Leave a Comment