how to dynamically re-generate random numbers in a table

Discussion in 'JavaScript' started by George Lucas, Nov 19, 2009.

  1. #1
    i have a table with a couple random numbers, and i want to click a button that will dynamically regenerate the numbers each time the button is clicked without re-generating the entire table., im using DOM and innerhtml for these random numbers. heres the javascript and html code. so far, it just generates the random numbers when the page loads.


    var random = Math.floor(Math.random()*40 + 1) //sets variables for random numbers to generate
    var random2 = Math.floor(Math.random()*40 + 1)
    var random3 = Math.floor(Math.random()*40 + 1)
    var random4 = Math.floor(Math.random()*40 + 1)
    var random5 = Math.floor(Math.random()*40 + 1)
    var random6 = Math.floor(Math.random()*40 + 1)

    //create table
    function makeTable(lotto)

    document.getElementById("tableSpan").innerHTML = '<table border="1" id="lotto">';
    var caption=document.getElementById('lotto').createCaption();

    caption.innerHTML="JavaScript Random Numbers";

    var x=document.getElementById('lotto').insertRow(0);
    var cell1=x.insertCell(0);
    var cell2=x.insertCell(1);
    var cell3=x.insertCell(2);
    var cell4=x.insertCell(3);
    var cell5=x.insertCell(4);
    var cell6=x.insertCell(5);

    cell1.innerHTML='<td class = "normal">'+ random +'</td>';
    cell2.innerHTML='<td class = "normal">'+ random2 +'</td>';
    cell3.innerHTML='<td class = "normal">'+ random3 +'</td>';
    cell4.innerHTML='<td class = "normal">'+ random4 +'</td>';
    cell5.innerHTML='<td class = "normal">'+ random5 +'</td>';
    cell6.innerHTML='<td class = "red">'+ random6 +'</td>';
    }

    heres the HTML file:

    <body onload="makeTable('lotto');">

    <div id="container">

    <div id="header">
    <h1>Welcome</h1>
    </div>

    <div id="content">
    <span id="tableSpan"></span>
    <input type="button" value="Re-generate Numbers" onclick="makeTable('lotto');" />
    </div>

    {
     
    George Lucas, Nov 19, 2009 IP
  2. ajaXpert

    ajaXpert Member

    Messages:
    41
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #2
    Firstly create the table with html:

    <table id="lotto">
    <tr>
    <td class="normal"></td>
    <td class="normal"></td>
    <td class="normal"></td>
    <td class="normal"></td>
    <td class="normal"></td>
    <td class="red"></td>
    </tr>
    </table>
    <script type="text/javascript">printNumbers();</script>

    The javascript function:

    function printNumbers(){
    var tbl = document.getElementById("lotto");
    var row = tbl.rows[0];
    lim = row.cells.length;
    for(i=0; i<lim; i++){
    row.cells.innerHTML = Math.floor(Math.random()*40 + 1);
    }
    }
     
    ajaXpert, Nov 19, 2009 IP