Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to HTML form without losing current form input information in Javascript

I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:

document.getElementById('theform_div').innerHTML = 
    document.getElementById('theform_div').innerHTML + 'this is the new stuff';

How can I get it to keep whatever has be enetered in the form and also add the new field to the end?

like image 506
David Avatar asked Feb 03 '10 14:02

David


2 Answers

Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.

You need to build a separate DOM tree and add it by calling appendChild.

For example:

var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);   

This is much easier to do using jQuery.

like image 75
SLaks Avatar answered Sep 24 '22 22:09

SLaks


Step One:

Add jQuery to your headers:

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>

Step Two:

Append, don't replace, data to your DIV like this:

$("#theform_div").append("your_new_html_goes_here");
like image 40
tambler Avatar answered Sep 22 '22 22:09

tambler