Dynamically created form field loses value when new field is added
I am creating a dynamic set of fields with javascript. I am using the following function to add fields (this function actually adds multiple fields)
// 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+"'/> <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'/> <a href='javascript:addObject();'>+ add question</a><br/><br/><hr/><br/></div>";
}
I use innerHTML
instead append
because there is a lot of code that I will need to add, the markup is so shorter.
Now my problem is that whenever I add (or remove) a field, all data from other dynamically generated data will be lost. How can I fix this? Storing the value and then adding it to each field would be again, very difficult in my case. Any ideas?
a source to share
Setting the innerHTML of the parent element causes all content to be serialized and re-parsed, losing all values โโin the process (values โโare not converted to sequential values โโin value attributes). I can think of three workarounds:
- Create your outer div (testContainer) with createElement, set its innerHTML and then add the div to the parent element
- Create all elements using DOM. It's trivial to create a bunch of helper functions to make element creation easier.
- Use jQuery, which does all of this for you:
$(location).append('html goes here');
a source to share