javascript - Adding a textbox to div without losing values -
this question has answer here:
- innerhtml append instead of replacing 3 answers
i've div container , button. whenever click button, empty textbox added div. now, problem whenever click button, textbox added, values of others removed.
the function made this:
function addtextbox() { document.getelementbyid("txtlist").innerhtml += "<input type='text'>"; }
what happening under hood here when append dom text using innerhtml
rewriting section of html. editing textlist innerhtml
execute new paint of element , information parsed again. means loose user interaction.
to update dom elements there methods enable that. namely document.createelement
, document.appendchild
.
by appending dom element opposed concatenating innerhtml(text)
forcing limited paint of specific area. leaves rest of dom in tact.
your code here
function addtextbox() { document.getelementbyid("txtlist").innerhtml += "<input type='text'>"; }
becomes more following
function addtextbox() { var textel = document.getelementbyid("txtlist"); var input = document.createelement("input"); input.type = 'text'; textel.appendchild(input); }
Comments
Post a Comment