Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda