I am back with a problem again (please cooperate with my silly questions, i am very new to JavaScript). I am trying for understanding the concept of dynamic tables in JavaS
JS
function createTable() {
var a, b, tableElem, rowElem, colElem;
a = document.getElementById('tb1').value;
b = document.getElementById('tb2').value;
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableElem = document.createElement('table');
for (var i = 0; i < a; i++) {
rowElem = document.createElement('tr');
for (var j = 0; j < b; j++) {
colElem = document.createElement('td');
colElem.appendChild(document.createTextNode(j + 1)); //to print cell number
rowElem.appendChild(colElem);
}
tableElem.appendChild(rowElem);
}
document.body.appendChild(tableElem);
}
}
JSFiddle
http://jsfiddle.net/mprRb/1/
here's another solution using innerHTML
<script type = "text/javascript">
function createTable(){
var a = document.getElementById("tb1").value;
var b = document.getElementById("tb2").value;
var resultTable = '<table>';
if(a=="" || b==""){
alert("Please enter some numeric value");
}else{
for(var i=0;i<parseInt(a);i++){
resultTable += '<tr>';
for (var j=0;j<parseInt(b);j++)
resultTable +='<td><\/td>';
}
resultTable +='<\/tr>';
}
resultTable+='<\/table';
}
return resultTable;
}
</script>
after that, just add the result to whatever element you want using innerHTML, for example, if you have:
<div id='myElement'></div>
then you can add the table to the element (inside any js function) like this:
var targetElement = document.getElementById('myElement');
targetElement.innerHTML = createTable();
otherwise, you can just delete the line:
return resultTable;
and add the table to the element directly inside the function, like this:
var target = document.getElementById('myElement');
target.innerHTML=resultTable;
Here is your function:
function createTable(){
var a = document.getElementById("tb1").value;
var b = document.getElementById("tb2").value;
if(a=="" || b==""){
alert("Please enter some numeric value");
}else{
row=new Array();
cell=new Array();
row_num=parseInt(a); //edit this value to suit
cell_num=parseInt(b); //edit this value to suit
tab=document.createElement('table');
tab.setAttribute('id','newtable');
tbo=document.createElement('tbody');
for(c=0;c<row_num;c++){
row[c]=document.createElement('tr');
for(k=0;k<cell_num;k++) {
cell[k]=document.createElement('td');
cont=document.createTextNode((c+1)*(k+1))
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);//'myTable' is the parent control of your table, change it as per your requirements
}
}
}
Add this attribute to your button b1 onclick="createTable();"