Reputation: 1683
So I am creating form which can add custom fields to. I was originally using .innerHTML to add these additional forms. When I added new forms, any values in the previous ones were wiped.
So the html looks like this:
<button id="add"></button>
<div id = "outer_div"></div>
The initial javascript looked like this:
$(document).on("click", "#add", function()
{
getElementById("outer_div").innerHTML +='<input></input>';
});
Say you add two fields. You write something in the first field. You press the #add
button. What you wrote in the first field is now cleared.
I decided to use jquery and it no longer had this problem:
$(document).on("click", "#add", function()
{
$("#outer_div").append('<input></input>');
});
Why?
Upvotes: 1
Views: 941
Reputation: 2300
The issue is because of the "+=" operator:
getElementById("outer_div").innerHTML +='<input></input>';
What is happening is you are resetting the complete value of innerHTML every time, which effectively removes the existing fields and re-adds them.
The reason this does not happen with jQuery is that underneath the hood, jQuery is using the Javascript .appendChild
function to directly insert the new elements in the DOM.
The pure javascript version for your example would be something like this:
var inpElem = document.createElement("input");
document.getElementById("outer_div").appendChild(inpElem);
Upvotes: 2
Reputation: 5528
That's because the values written into the fields aren't considered to be a part of the existing HTML. So when you append the new HTML to the form, the values are lost because as far as innerHTML is concerned, they don't exist anyway. A probable fix can be to temporarily store all the form's values in variables, then once the new HTML is appended to the old, reassign them to the proper fields.
Upvotes: 0