I have had this problem for a while and it has been driving me crazy! It’s not crashing my site or making it unusable but is infuriating nonetheless. I have a tag so users can create up to ten questions to any given answer inside a form, and a javascript button so that they can add another answer. The trouble I am having is that if they add some answer text fields with the button and fill them in, when they go to add another answer with the button it over-writes all of the answers they have just submitted! The link to the jsfiddle is http://jsfiddle.net/EkUmG/ and here is the code from my actual html document that is pertinent (i would include the entire file but there is php on it so you couldnt just drag and drop it into the browser anyway)
- thanks for any help in advance
here is the html
<div id='buttons'></div>
(and yes i realize that is an inappropriate name for that div, sorry about that)
and here is the javascript
<script type="text/javascript">
var answers = 0;
var inHTML = "";
function addAnswer()
{
if(answers < 10){
write = document.getElementById('buttons');
write.innerHTML = write.innerHTML + "answer: <input type=\"text\" name=\"answer" + answers + "\" /> <br>";
answers = answers + 1;}
}
</script>
By writing to the
innerHTMLproperty you make the browser re-parse all the content, therfore resetting the input fields’ values.Instead, use
insertAdjacentHTML(Demo).Note that this method is supported by FF only since version 8. You might use this polyfill or go with @Stano’s solution if you need to support lower versions.