var file = document.getElementById('file'), removeBtn = document.getElementById('remove'); removeBtn.addEventListener('click', function() { file.value = ''; }, false); 
 <input type="file" id="file"/> <br /> <input type="button" id="remove" value="remove" /> <br /> <br /> <input type="file" id="file"/> <br /> <input type="button" id="remove" value="remove" /> <br /> <br /> <input type="file" id="file"/> <br /> <input type="button" id="remove" value="remove" /> <br /> <br /> 

How to change the script correctly so that only the file under which the delete button is located can be deleted?

    1 answer 1

    First, it’s impossible to have two identical id on one page. Secondly, it is worth changing the layout so that the field and the button unite something. For example, a common parent element.

     var removeButtons = document.getElementsByClassName('remove'); for(var i = 0; i < removeButtons.length; i++) removeButtons[i].addEventListener('click', function(event) { var parent = event.target.parentNode; for(var x = 0; x < parent.childNodes.length; x++) { if(parent.childNodes[x].nodeName == 'INPUT' && parent.childNodes[x].type == 'file') parent.childNodes[x].value = ''; } }); 
     <p> <input type="file" /> <br /> <input type="button" class="remove" value="remove" /> </p> <p> <input type="file" /> <br /> <input type="button" class="remove" value="remove" /> </p> <p> <input type="file" /> <br /> <input type="button" class="remove" value="remove" /> </p> 

    If interacting inputs were written in a row, without tags and text between them, it could be even simpler using the previousSibling attribute:

     event.target.previousSibling.value = ''; 

    And finally, one more important note: the browser security system may not allow changing the value in the file type field. So it is better not to try.