Home > OS >  multiple user upload image fields using javascript
multiple user upload image fields using javascript

Time:06-08

so I have an upload image button that works so the user can upload an image from their computer to the website I'm working on and the image shows on the page. I need help figuring out how to make multiple of these image upload fields that allows the user to upload a different image to each field. so far I can only get one to work. heres my code:

<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;">Upload Image</label></p>
<p><img id="output" width="200"></p>

<script>
var loadFile = function(event) {
    var image = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
};
</script>

CodePudding user response:

Try using "multiple" attribute.

HTML

<input type="file" id="files" name="files" multiple>

JS

var files = document.getElementById("files").addEventListener("change", function(e) {
  console.log(e.target.files)
})

Is that what you want or have I understood you wrong?

CodePudding user response:

I'm not 100% sure I understood correctly your question, but if you want to add multiple add buttons you should use JS to select all the inputs and properly attach your event listeners:

const inputs = document.querySelectorAll("[name=image]")
const outputs = document.querySelectorAll(".output")

inputs.forEach((i, idx) => {
  const o = outputs[idx]
  i.onchange = e => {
    const file = e.target.files[0]
    const url = URL.createObjectURL(file)
    o.src = url
  }
})
<p><input type="file" accept="image/*" name="image" id="file1" style="display: none;"></p>
<p><label for="file1" style="cursor: pointer;">Upload Image</label></p>
<p><img  width="200"></p>
<p><input type="file" accept="image/*" name="image" id="file2" style="display: none;"></p>
<p><label for="file2" style="cursor: pointer;">Upload Image</label></p>
<p><img  width="200"></p>
<p><input type="file" accept="image/*" name="image" id="file3" style="display: none;"></p>
<p><label for="file3" style="cursor: pointer;">Upload Image</label></p>
<p><img  width="200"></p>
<p><input type="file" accept="image/*" name="image" id="file4" style="display: none;"></p>
<p><label for="file4" style="cursor: pointer;">Upload Image</label></p>
<p><img  width="200"></p>

  • Related