Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
Why are the values of my previous input field disappearing when I click on the ADD ANOTHER IMAGE button?
<html>
    <head>

    </head>
    <body>
        <form action="" enctype="multipart/form-data" method="post">
            <input type="file" name="pic" accept="image/*" id="insert-file" class="ins=file">
            <input type="submit" id="submit-btn" class="submit-btn">
            <button id="add-img" type="button">ADD ANOTHER IMAGE</button>
            <div id="new-field"></div>
            <script src="{{ url_for('static', filename='upload.js') }}"></script>
        </form>
    </body>
</html>

This is my template and the following is upload.js

const addImg = document.getElementById('add-img')
const newField = document.getElementById('new-field')

addImg.addEventListener('click', function() {
    newField.innerHTML += `
    <input type="file" name="pic" accept="image/*" class="ins=file">
    <input type="submit" class="submit-btn">
    `
})

As you can see, a new input field will be created when a user clicks on the ADD ANOTHER IMAGE button but the image selected in that input field will disappear when the button is clicked and it will show, "No file chosen" despite the user selecting a file before clicking on the ADD ANOTHER IMAGE. I suspect that it is because I am getting rid of the value of the input field when creating a new with the ADD ANOTHER IMAGE button. (it is there in the JS code)

Anyway, how can I fix this? I want the user to be able to click on the ADD ANOTHER IMAGE button and the input field to still contain the file that they selected previously.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

using .innerHTML += is converting what is currently on the dom in to a string, then putting it back in to the dom which causes it to become a new element.

use insertAdjacentHTML to insert a string of html in to the dom to keep the existing elements mdn docs

addImg.addEventListener('click', function() {
    newField.insertAdjacentHTML('beforeend',`
    <input type="file" name="pic" accept="image/*" class="ins=file">
    <input type="submit" class="submit-btn">
    `)
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda