-1

I am creating a 2d array with user input. How can I display the input on to a 3 by 3 table?

<script language = javascript>
var b = [];
for(var i=0; i<3; i++){
b[i] = [];
for(var j=0; j<3; j++){
b[i][j] = window.prompt("b["+(i+1)+","+(j+1)+"] = ?");
}
}
</script>
</head>
<body>
<table width="80%" border="2" cellspacing="0" cellpadding="0">
  <tr>
<td> </td>
<td>&nbsp;</td>
<td>&nbsp;</td>
 </tr>
 <tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
Jessica
  • 179
  • 1
  • 4
  • 15

2 Answers2

2

You can do something like this..

<!DOCTYPE html>
<html>
<head>
<style>
table {
    font: 11px/24px Verdana, Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 320px;
    }

td {
    border: 1px solid #CCC;
    padding: 0 0.5em;
    }


</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>

$(document).ready(function(){



$("#myRandomizeBtn").bind("click",randomizeHandler); 

function randomizeHandler(evt){     
var root=document.getElementById('mydiv');
var tab=document.createElement('table');
tab.className="mytable";
var tbo=document.createElement('tbody');
var row, cell;
var n = 3;  
var data;    

for (i=0; i<n; i++)
{
    row=document.createElement('tr');
    for(var j=0;j<n;j++){
        cell=document.createElement('td');
        data =window.prompt("b["+(i+1)+","+(j+1)+"] = ?"); 
        cell.appendChild(document.createTextNode(data));
        row.appendChild(cell);
    }
    tbo.appendChild(row);
}
tab.appendChild(tbo);
root.appendChild(tab);




   }  



});
</script>
</head>
<body>
    <div id='mydiv'></div>
    <button id = "myRandomizeBtn">Randomize</button> 
</body></html>

here is a working fiddle

Bharath R
  • 1,481
  • 1
  • 11
  • 23
1

You can use following code to traverse and push value

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop

       col.innerText = b[i][j]; //Set your value here   
   }  
}

Working Demo

Reference for Traversing from @John Hartsock answer at How do I iterate through table rows and cells in javascript?

Community
  • 1
  • 1
Satpal
  • 126,885
  • 12
  • 146
  • 163