The situation is the following: I've got a form with some input textboxes and a button that calls the add()
function when clicked. This is the HTML code:
<div id="resultdiv" style="display: none" align="center">
<TEXTAREA id="resultcode" style="width: 100%; height: 70%"></TEXTAREA>
</div>
<div align="center" width="100%">
<form>
<input type="text" name="atrib" value="atrib name"><input type="text" name="val" value="default value"><br>
<div id="bar"></div>
<input type="button" value="Add" onclick="add();"><input type="button" value="Generate" onclick="gen();">
</form>
</div>
The add()
function adds two new input forms into de div with id bar
. This is working without any troubles, the problem is that if I add a new textbox and write some value different from the default one, as soon as I click again on the Add button, a new textbox is created, but the value of the previous created textbox is changed to the default value again!!!
Here is the JavaScript code with the add()
function:
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
var element2 = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "atrib name");
element.setAttribute("name", "atrib");
element2.setAttribute("type", "text");
element2.setAttribute("value", "default value");
element2.setAttribute("name", "val");
// the div id, where new fields are to be added
var bar = document.getElementById("bar");
//Append the element in page (in span).
bar.appendChild(element);
bar.appendChild(element2);
bar.innerHTML += "<br>";
}
And here a jsfiddle of the whole application: http://jsfiddle.net/3a1kojgn/
I don't understand why the value of the previous dynamicly added textbox resets when adding another one if I'm creating brand new elements on each add()
call. Any hint guys?
";` , it works – Flakes Feb 18 '15 at 12:13