Steven Sugiarto Wijaya Steven Sugiarto Wijaya - 2 months ago 8
Javascript Question

looping in javascript using array

i have html code for input file, it have id and name

<input type="file" id="file1" name="my_field[]" class="image-upload" />


for validate input form, i check value using id but i have many input.

var count=0;
if(document.getElementById("file1").value != "") {
// you have a file
count = count + 1;
}
if(document.getElementById("file2").value != "") {
// you have a file
count = count + 1;
}


i want using getElementByName with array. this is what i have try:

for(i=0;i<6;i++)
{
if(document.getElementByName("my_field["+i+"]").value != "") {
// you have a file
count = count + 1;
}
}


Still not working. any suggest?

Answer

You already have unique id values. Use those.

...
if(document.getElementById("file" + my_field[i].toString()).value != "") {
...
Comments