我制作了一个表单,当我单击按钮时添加一些输入。这个按钮的功能是用javascript实现的。
但是当我点击它时,我所有的输入都变成空,我不希望这样。我想将信息保留在已有的输入中。
出了什么问题以及如何修复它?
var div = document.getElementById('participant');
function AjoutParticipant() {
var ex = document.getElementsByClassName("bouton_plus");
for (i = 0; i < ex.length; i++) {
ex[i].style.display = "none";
}
div.innerHTML += '<label>Nom :</label><input type="text" name="nom[]" />' +
'<label id="pre-decal">Prenom :</label><input type="text" name="prenom[]" />' +
'<label id="ent-decal">Entreprise :</label><input type="text" name="entreprise" /><br/>' +
'<button class="bouton_plus" type="button" onclick="AjoutParticipant()"><i class="fa fa-fw fa-plus"></i> Ajouter Participant</button>'
}
<fieldset id="participant">
<legend>Participant(s)</legend>
<label>Nom :</label><input type="text" name="nom[]" />
<label>Prenom :</label><input type="text" name="prenom[]" />
<label>Entreprise :</label><input type="text" name="entreprise" /><br/>
<button class="bouton_plus" type="button" onclick="AjoutParticipant()"><i class="fa fa-fw fa-plus"></i> Ajouter Participant</button>
</fieldset>
最佳答案
您正在获取 div 的 innerHTML
,向其附加一些新的 HTML,然后将其分配回来。
HTML 中的值
属性代表默认值,因此当用户在其中键入内容时它不会更新。
因此,当您覆盖 innerHTML
时,您会将输入重置为默认值。
不要使用innerHTML
。
相反,请使用 createElement
和 appendChild
等 DOM 方法向 div 添加新内容,而无需重写现有内容。
关于javascript - 当我点击按钮时,我的输入标签变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581994/