JavaScript- dynamically adding input to a page -
i using javascript add div on fly. div should contain form input 'name' attribute changes in value incrementally.
i have managed this- have 2 problems.
first problem:
the first div created cancelled out next dynamically created div.
thus, when submit form, first dynamically created imput form blank- subsequent ones have values on them.
my code :
html
<div id="dynamicdivsection"></div> <button id="addbutton">add box</button> <div id="boxes"> <div class="box"> <input type="text" id='dynamic-imput' name=""> </div> </div>
javascript
var addbutton = document.getelementbyid("addbutton"); var key = 1; addbutton.addeventlistener("click", function() { key++; document.getelementbyid('dynamic-imput').name = 'ser['+key+'][\'name\']'; var boxes = document.getelementbyid("boxes"); var head = document.getelementbyid("dynamicdivsection"); var clone = boxes.firstelementchild.clonenode(true); head.appendchild(clone); });
i suspect problem causing this:
document.getelementbyid('dynamic-imput').name = 'ser['+key+'][\'name\']';
i.e when create dynamic div creates several inputs on page contain same id. if correct, perhaps teh solution change id of newly created imput - however, not sure how change id of dynamically created imput.
second problem.
i want each dynamically created div go top of page; i.e placed before earlier created dynamic div- however, @ moment each dynamically created div go directly under first dynamically created div.
you can insert first child with:
parent.insertadjacentelement('afterbegin', nodetoinsert);
you can , set attributes such id
setattribute , getattribute. though i'm not sure why need id here, simpler not have 1 , select element class.
var addbutton = document.getelementbyid("addbutton"); var key = 1; addbutton.addeventlistener("click", function() { key++; document.getelementbyid('dynamic-imput').name = 'ser['+key+'][\'name\']'; var boxes = document.getelementbyid("boxes"); var head = document.getelementbyid("dynamicdivsection"); var clone = boxes.firstelementchild.clonenode(true); var clonedinput = clone.firstelementchild; clonedinput.setattribute('id', clonedinput.getattribute('id') + '-' + head.children.length); head.insertadjacentelement('afterbegin', clone); });
<div id="dynamicdivsection"></div> <button id="addbutton">add box</button> <div id="boxes"> <div class="box"> <input type="text" id='dynamic-imput' name=""> </div> </div>
Comments
Post a Comment