Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Wygekas's avatar

After copying input file, can't submit both values

Hi, i have problem that <input type="file" ....> that was filled before copying can't be submited together with the original.

HTML:

<div>
<label for="img[0][0]">
  <img class="w-full h-full object-contain" src="" id="img[0][0]_img">
</label>
	<input type="file" name="img[0][0]" id="img[0][0]" class="hidden" //this input is filled before copying whole <div>
	<button type="button" onclick="add_service_img(this.parentNode)">+</button>
</div>

Javascript:

function add_service_img(div){
	var clone = div.cloneNode(true);
	div.parentNode.insertBefore(clone, div.nextSibling);
	recalc_services(); //here i update [0][0] to be unique. New element would be [0][1]
}

The problem is here: If input was empty before copying, all works good. But if input was filled before copying $request gets only last image uploaded. Both cases while analyzing network, payload sent is correct (has both img[0][0] and img[0][1], but for some reason $request is missing first element. Why?

0 likes
5 replies
LaryAI's avatar
Level 58

The issue is that the cloned input element still has the same name as the original input element, so when the form is submitted, only the last input element with that name is included in the request. To fix this, you can update the name of the cloned input element to be unique. Here's an example of how you can update the add_service_img function to do this:

function add_service_img(div){
    var clone = div.cloneNode(true);
    var input = clone.querySelector('input[type="file"]');
    var index = input.name.match(/\d+/)[0];
    index++;
    input.name = input.name.replace(/\d+/, index);
    div.parentNode.insertBefore(clone, div.nextSibling);
    recalc_services();
}

This code finds the input element in the cloned div, extracts the index from its name, increments the index, and updates the name of the input element to include the new index. This ensures that each input element has a unique name and will be included in the request.

Wygekas's avatar

@LaryAI Nice guess, but names and ID's are unique because after element is pasted, all element names and ID's are refreshed to be unique (confirmed with inspect element) . To fellow humans your suggestion is not quite correct.

Snapey's avatar

how does first input get filled when it is hidden?

Wygekas's avatar

@snapey I have label which has image inside. So when you click on it, you can upload your file to input and then javascript makes preview of what you uploaded. I updated post to include this area.

<label for="img[0][0]">
  <img class="w-full h-full object-contain" src=" " id="img[0][0]_img">
</label>
Snapey's avatar

doesnt explain how the hidden file input gets a value

Please or to participate in this conversation.