添加到HTML表单而不会丢失Javascript中的当前表单输入信息

时间:2010-02-03 14:51:12

标签: javascript forms innerhtml

我有一个下拉列表,它根据所选的选项构建表单。因此,如果有人选择'foobar',它会显示一个文本字段,如果他们选择'cheese',它会显示单选按钮。然后,用户可以在这些表单中输入数据。唯一的问题是,当他们添加新的表单元素时,所有其他信息都将被删除。我目前正在使用以下内容添加到表单中:

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

如何让它保留表格中的任何内容,并将新字段添加到最后?

5 个答案:

答案 0 :(得分:13)

设置innerHTML会破坏元素的内容并从HTML重建它。

您需要构建一个单独的DOM树,并通过调用appendChild来添加它。

例如:

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

使用jQuery更容易做到这一点。

答案 1 :(得分:4)

第一步:

将jQuery添加到标题中:

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

第二步:

将DIV中的数据附加,不要替换为:

$("#theform_div").append("your_new_html_goes_here");

答案 2 :(得分:2)

不要使用innerHTML来创建表单元素。使用innerHTML,您将使用新HTML覆盖旧HTML,这将重新创建所有元素。相反,您需要使用DOM来创建和追加元素。

示例

function addRadioElement()
{
    var frm = document.getElementById("form_container");
    var newEl = document.createElement("input");
    newEl.type = "radio";
    newEl.name = "foo";
    newEl.value = "bar";
    frm.appendChild(newEl);        
}

答案 3 :(得分:2)

在不使用框架(如jQuery,Dojo,YUI)的情况下执行此操作的最正确方法是:

var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);

document.getElementById('theform_div').appendChild(div);

innerHTML虽然受到大多数浏览器的支持,但不符合标准,因此无法保证正常工作。

答案 4 :(得分:0)

我建议使用jQuery及其append函数。