2
所以下面的代碼動態地添加使用javascript的html表單元素。 問題是,如果我添加新的html表單元素,然後用我想要的(即鍵入abc)更新它,然後單擊添加另一個它抹去我以前輸入的內容並將其重置爲其原始文本。動態添加html表單元素和更新的數據得到重置
例如:
點擊「添加更多的數據」
然後我改變「名」約翰「姓」哆。
然後我再次點擊「添加更多的數據」和約翰已被重置爲「名」和母鹿已重置爲「姓」。
我該如何解決這個問題?
<script>
var x = 1;
function add() {
var fooId = "foo";
for (i=1; i<=3; i++)
{
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", fooId+x+i);
element.setAttribute("name", fooId+x+i);
element.setAttribute("id", fooId+x+i);
if(i==1){
element.setAttribute("value", "First name");
}
if(i==2){
element.setAttribute("value", "Last name");
}
if(i==3){
element.setAttribute("value", "age");
}
var foo = document.getElementById("fooBar");
foo.appendChild(element);
foo.innerHTML += ' ';
}
i++;
var br = document.createElement("br");
foo.appendChild(br);
x++;
}
</SCRIPT>
<body>
<center>
<form id="form" name="form" action="test.php" method="post" enctype="multipart/form-data">
<input type="text" id="foo01" name="foo01" value="first name">
<input type="text" id="foo02" name="foo02" value="last name"/>
<input type="text" id="foo03" name="foo03" value="age">
<br>
<span id="fooBar"></span>
<FORM>
<INPUT type="button" value="Add more data" onclick="add()"/>
<input type="submit" value="Submit">
</center>
</FORM>
</form>
</body>
完美工作,感謝。 – user2484214