I want to create multiple DataTransfer objects in a for loop & then use them. But it is not working.
var cars = ["test1", "test2", "test3", "test4"];
for(let i = 0; i < cars.length; i++) {
var cars[i] = new DataTransfer();
}
This is showing: Uncaught SyntaxError: Unexpected token '['
Then I would like to use them according to the id or class like:
<span id="testing" value="test1"></span>
var f = new File([""], "filename.txt", {type: "text/plain"})
$("#testing").attr('value').items.add(f);
With above I get this error : Cannot read properties of undefined (reading 'add')
I don't know what I am missing. Thanks in advance!
This is showing: Uncaught SyntaxError: Unexpected token '['
The issue is your statement in your for loop
var cars = ["test1", "test2", "test3", "test4"];
for(let i = 0; i < cars.length; i++) {
// You are trying to declare a variable name here, and brackets are not valid characters in variable names
var cars[i] = new DataTransfer();
}
if you're just trying to set the value at each index of your array, you can just set them without declaring a variable:
var cars = ["test1", "test2", "test3", "test4"];
for(let i = 0; i < cars.length; i++) {
cars[i] = new DataTransfer();
}
With above I get this error : Cannot read properties of undefined (reading 'add')
This is because the value of your span is a string "test1" which does not have a method/property called items. I can only guess you're trying to use your DataTransfer object there, so you would need to access it in a different way. Perhaps in your javascript you could set up an object with keys to access your objects:
var cars = ["test1", "test2", "test3", "test4"];
var dataTransfers = {};
for(let i = 0; i < cars.length; i++) {
// dataTrasnfers.test1 = new DataTransfer() when i = 1
dataTransfers[cars[i]] = new DataTransfer();
}
From there, dataTransfers.test1, dataTransfers.test2, dataTransfers.test3, dataTransfers.test4
are all valid. You can continue grabbing those names from your span values.