问题
i am using this code:
<html>
<head>
<title>Dynamic Form</title>
<script type="text/javascript">
var i = 6;
function CreateTextbox(){
createTextbox.innerHTML = createTextbox.innerHTML
+'<input type=text name="flow'+i+'"/>'
i++;
}
</script>
</head>
<body>
<form name="form" action="post">
<input type="button" name="what" value="clickHere" onClick="CreateTextbox()"/>
<div id="createTextbox"></div>
</form>
</body>
when i add a new textbox, the value that was entered in the previous textbox is deleted. how can i retain it?
回答1:
Adding HTML element by concatenating the innerHTML is very slow and that is causing the values to be cleared, since the container (the div createTextbox
) and all the childs are re-created on each innerHTML assignment.
I suggest you to create the input elements programmatically with document.createElement and append the elements using to the container div using appendChild:
window.onload = function () {
var createTextbox = function () {
var i = 6,
container = document.getElementById('createTextbox');
return function () {
var div = document.createElement('div'),
input = document.createElement('input');
input.type= "text";
input.name = "flow" + i;
div.appendChild(input);
container.appendChild(div);
i++;
}
}();
// event binding
document.getElementById('addButton').onclick = createTextbox;
}
Check the above code working here.
回答2:
You're probably forcing the browser to recreate the element when you redefine its innerHTML property, which subsequently causes you to lose its value in the process.
Can this be done with a
var elem = document.createElement("input");
someDOMElement.childNodes.add(elem);
combination?
来源:https://stackoverflow.com/questions/1391875/how-do-i-retain-the-value-of-dynamically-added-textboxes