简体   繁体   English

使用javascript保留文本字段的值

[英]Preserve value of the text field with javascript

I build a little snippet with javascript to add more fields by clicking a button. 我用JavaScript构建了一个小片段,以通过单击按钮添加更多字段。 It works fine and add the field as it should but it discards the values of the already existing fields on clicking the add more button. 它可以正常工作并按需添加字段,但是在单击添加更多按钮时,它会丢弃现有字段的值。

You can run the snippet below to check the issue ... Please add 2-3 fields and type something in those fields and then add another field. 您可以运行下面的代码片段来检查问题...请添加2-3个字段,然后在这些字段中键入内容,然后添加另一个字段。 You'll see what is happening. 您会看到发生了什么。

 var fldsContainer = document.getElementById('fields'); var fld = '<p><input name="test[]" type="text"></p>'; function addField() { fldsContainer.innerHTML += fld; } 
 <div id="fields"></div> <button onclick="addField()">Add More Field</button> 

I know in jQuery we can simply .append() but I need a solution in javascript. 我知道在jQuery中我们可以简单地使用.append()但我需要使用javascript解决方案。 Is there append method in javascript? javascript中有追加方法吗?

Or any other method to resolve my issue would be appreciated :) 或任何其他方法来解决我的问题,将不胜感激:)

It is because the content of fldsContainer is rerendered every time with a brand new list of fields. 这是因为fldsContainer的内容每次都使用全新的字段列表重新呈现。 You need to append to the container. 您需要附加到容器。 Try something like the insertAdjacentHTML() method. 尝试使用诸如insertAdjacentHTML()方法之类的方法。

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/zh-CN/docs/Web/API/Element/insertAdjacentHTML

 var fldsContainer = document.getElementById('fields'); var fld = '<p><input name="test[]" type="text"></p>'; function addField() { fldsContainer.insertAdjacentHTML('beforeend', fld); } 
 <div id="fields"></div> <button onclick="addField()">Add More Field</button> 

It may seem larger and maybe overkill but i prefer tracking all my inputs into an array so that i separate myself from needing to possibly query DOM elements in future. 它看起来可能更大,并且可能会矫kill过正,但是我更喜欢将我所有的输入都跟踪到一个数组中,这样我就不必再需要将来查询DOM元素了。

 var fldsContainer = document.getElementById('fields'); var fields = []; function render() { fldsContainer.innerHTML = getFields(); } function addField() { fields.push(fields.length ? getField(fields.length) : getField(0)); render(); } function setValue(input, i) { fields[i].value = input.value; } function getFields() { var str = '' fields.forEach(function(field) { str += (`<p><input name="${field.name}" value="${field.value}" type="text" onchange="setValue(this, ${field.index})"></p>`); }); return str; } function getField(index) { return { index, name: `test${index}`, value: '' } } 
 <div id="fields"></div> <button onclick="addField()">Add More Field</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM