I have the following JavaScript which generates text-inputs dynamically and inserts them into a div. This code works fine, but if I type text into the field, then click the button to add another field I lose the text I typed in the first field.
I made a jFiddle - but for some reason it's not working. The same code works fine in my browser though.
Here's the function in question:
var optCount = 0;
function addOption(type){
var cont = document.getElementById('new'+type+'Opts');
cont.innerHTML = cont.innerHTML + "<span style='display:block;' id='opt" + optCount + "'><input type='text' style='width:80%;' /><a href='#' style='color:red; text-decoration:none; font-size:.6em;' onclick=\"return delOpt('opt" + optCount + "');\">[x]</a><br /></span>";
optCount++;
return false;
}
How can I maintain the values of the existing fields when adding additional fields?
addOption, since that's only added at document ready, and is being referenced when the dom loads. Just change the jsfiddle option in the top left corner to "No wrap - in <head>", and your code will execute. jsfiddle.net/PBp4g/4 (Note, this doesn't fix your problem, it just fixes your fiddle)