Search code examples
javascriptarraysgetelementbyid

getelementbyid list in javascript


I'm trying to create a loop that will put values from inputs in an array. The point is that I have 81 inputs and their ids are "cells-[x]".

What I tried to do is

<script type="text/javascript">
    var test = [];
    for(i=0;i<80;i++){
        test[i]=(document.getElementById('cell-[i]').value);
    }
</script>

but it's not working.

B.T.W, I might have made a mistake in the for loop itself, but it is not my point(i'm only a beginner).


Solution

  • Two things:

    1. Your 'cell-[i]' is all in a string, so each time it thinks you're taking the value: 'cell-[i]'. Replace your parameter in getElementById with:

    ('cell-[' + i + ']').
    

    2. Try:

    test.push(document.getElementById('cell-[' + i + ']').value)
    

    That should do it.