0

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?

asked May 7, 2013 at 14:33
1
  • 1
    It's not finding 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) Commented May 7, 2013 at 14:40

1 Answer 1

2

Don't replace the entire contents of the div every time. Instead, just create the new option and append it.

var cont = document.getElementById("new"+type+"Opts");
var span = document.createElement('span');
span.className = 'block';
span.id = "opt" + optCount;
span.innerHTML = "<input type='text' class='width80' /><a href='#' class='dellink' onclick=\"return delOpt('opt" + optCount + "');\">[x]</a><br />";
optCount++;
cont.appendChild(span);

http://jsfiddle.net/ExplosionPIlls/PBp4g/5/

answered May 7, 2013 at 14:40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.