简体   繁体   中英

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.

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">
    `)
})

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