PDA

View Full Version : Text field clears when adding html to div.



martynball
Apr 9th, 2012, 06:29 PM
Hey guys, I have a script which adds more text fields to a div in a form, but when it adds a new field the text in the others is cleared. :S

http://martynleeball.goodluckwith.us/



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Draw Somthing - Word Guess</title>
<script type="text/javascript">
function add_field(obj, count) {
//Count how many fields there is so the correct number can be added to the ID
var form_name = document.getElementById(obj);
var inputs = form_name.getElementsByTagName('input');
var g = 1;
//alert("Container: " + obj + ". Inputs: " + inputs.length);

for ( var i = 0; i < inputs.length; i++) {
var node = inputs[i];
if (node.getAttribute('type') == 'text') {
g++;
}
}

//Field to add to the form
if (!count) {
if (g < 9) {
var text_field_html = "<input type=\"text\" id=\"input" + g + "\" name=\"input" + g + "\" /><input type=\"button\" value=\"X\" onClick=\"remove_field(\'text_field_container\', this)\" id=\"close" + g + "\"/>";
form_name.innerHTML += text_field_html + "<br id=\"br_" + g + "\" />";
}
}
}
function remove_field(parent_id, r_obj) {
var parent = document.getElementById(parent_id);
var child = document.getElementById(r_obj.id);
var num = r_obj.id.charAt(r_obj.id.length-1);
var child2 = document.getElementById('input' + num);
var child3 = document.getElementById("br_" + num);

parent.removeChild(child); parent.removeChild(child2); parent.removeChild(child3);
}
</script>
</head>
<body>
<br />
<form id="add_words" action="test.php" method="post">
<div id="text_field_container">
<input type="text" id="input1" name="input1" /><input type="button" value="X" id="close1" onClick="remove_field('text_field_container', this)"/>
<br id="br_1" />
</div>
<input type="button" value="Add more..." onclick="add_field('text_field_container')" />
<input type="submit" value="Submit" onclick="" />
</form>
</body>
</html>

devnull69
Apr 10th, 2012, 11:15 AM
Changing the innerHTML of an element always causes the full element to be re-rendered. This will reset all changes to the content of the element.

You should change to using document.createElement(), .appendChild() and document.createTextNode() instead so that only single element will be added to the DOM which will keep the other elements unchanged.

martynball
Apr 10th, 2012, 04:54 PM
edit: never mind