javascript - Add element works but clears input value -
i have script below adds element form, text input field. adds new text input field if type first 1 add new field removes input text first one.
i cant see im going wrong here, im new javascript please go easy :)
function addanother() { var id = 1; var elemebt = document.getelementbyid('quest'); var number = elemebt.getelementsbytagname('*').length; var add = number + 1; var element = '<input type="text" name="question[]" id="quest'+ add + '" placeholder="example: previous experiance have?" class="form-control" id="cloan"><a id="name'+ add +'" onclick="removeele('+ add +')">remove</a>'; document.getelementbyid('quest').innerhtml += element; }
in javascript, following 2 statements practically identical:
str = str + ' more text '; str += ' more text ';
the key point here in end, value of str
completely overwritten.
in case, means innerhtml
of "quest" element overwritten , browser recreates it's children nodes, reseting state , input values.
to overcome this, can use appendchild
method first need create element append. easiest way given have string of html inject string dummy element using innerhtml
property:
var target = document.getelementbyid('target'); var tdiv = document.createelement('div'); var htmlstring = '<input type="text"></input>'; tdiv.innerhtml = htmlstring; target.appendchild(tdiv.children[0]);
<div id="target">keep content safe!</div>
Comments
Post a Comment