how to fill out the table with next values in array with one button

158 views Asked by At

say that my array value is as follows. var array = [1, 2, 3, 4, 5, 6, ...] how can I make it so that clicking the button can display the item in array one after another in different boxes?

for example..first click = array[0] second click = array[1] ...and so on.

below is my code so far. every time the button is clicked, it will only print all the values in array one by one to the same table.

<tr>
    <td><p id="result2"></p></td>
    <td><p id="result3"></p></td>
    ....
</tr>

<button onclick="clickBowl()">Bowl</button> 

JS:

var k = 0;

function clickBowl() {
    x = document.getElementById("result2").innerHTML = frameArr[k++];
}   
4

There are 4 answers

3
taxicala On BEST ANSWER

Try this:

HTML:

<tr id="results"></tr>

JS:

<script type="text/javascript">
    var i = 0, myArr = [0, 1, 2, 3, 4 ,5, 6, 7];
    function clickBowl() {
        if (i > myArr.length) return;
        var child = document.createElement("td");
        child.innerHTML = myArr[i++];
        document.getElementById("results").appendChild(child);
    }
</script>

That way, you define a global scope var i that each time you click on the bowl, you will add one after you use it in order to get the value with that key from your array and append a td child to your results row.

0
brroshan On

Taxicalas answer is correct but i'd like to post this jQuery version:

var array = [1, 2, 3, 4, 5, 6];

$(function(){
    $("button")
    .on("click", function(){
        if(array.length === 0) return;
        $("table").append("<tr><td>" + array[0] + "</td></tr>");
        array.shift();        
    });
});

The shift method of the array removes the first element.

https://jsfiddle.net/ztkdvz3m/

0
dfsq On

In your case it will be something like this:

var k = 0;

function clickBowl() {
    document.getElementById("result" + ++k).innerHTML = frameArr[k - 1];
}

Note, that you need one more value for the last slot (Frame 10).

Demo: https://jsfiddle.net/ed43L0ts/1/

0
Matt On

Building on previous answer

<table>
    <tr id="tableRow">
    </tr>
</table>

    <script type="text/javascript">
    var i = 0, array = [0, 1, 2, 3, 4 ,5, 6];

    function clickBowl() {
        var currentValue = array[i++];
        var tableData = document.createElement("td");
        tableData.innerHTML = "<p id=" + currentValue + ">" + currentValue + "</p>";
        document.querySelector("#tableRow").appendChild(tableData);
       }

    array.forEach (clickBowl);    
</script>