简体   繁体   中英

My input tag becomes empty when I click on a button

I made a form which add some input when I click on a button. The function of this button was made with javascript.

But when I click on it, all my inputs become empty and I don't want that. I want to keep information in inputs I already have.

What's going wrong and how can I fix it?

 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> 

You are taking the innerHTML of the div, appending some new HTML to it, then assigning it back.

The value attribute in HTML represents the default value, so it doesn't get updated when the user types something into it.

Consequently, you reset the inputs to the default value when you overwrite the innerHTML .


Don't use innerHTML .

Instead, use DOM methods like createElement and appendChild to add new content to the div without rewriting the existing content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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