Dynamically generated form field loses value when

2019-07-18 05:34发布

问题:

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?

回答1:

Setting the innerHTML of the parent element causes the entire content to be serialized and then re-parsed, losing all the values in the process (the values aren't serialized back into value attributes). I can think of three workarounds:

  1. Create your outer div (the testContainer) using createElement, set its innerHTML and then append the div into the parent element
  2. Create all the elements using DOM. It's trivial to create a bunch of helper functions to make creating the elements easier.
  3. Use jQuery which does all this for you: $(location).append('html goes here');