Hermione Hermione - 3 days ago 5
Javascript Question

I want to call the same function multiple times, without loosing its previews outputs. I don't want to use a database. What should I use?

I need to generate multiple tables, by calling the same function. When I do this, the previews table gets lost, because I recall the function. I am new to JavaScript. Can you suggest me what should I use. Note: I don't want to use a database to save the information. I am not sure if I should do it with Ajax or there is some other simple way, just by using JavaScript.

<form>
Row: <input type="text" id="x" />
Columns:<input type="text" id="y" />
<input type="button" value="OK" onclick='createTable();'></input>
</form>
<div id="table"></div>
<script>
function createTable(){

var x= document.getElementById("x").value;
var y= document.getElementById("y").value;

var rX = parseInt(x);
var cY = parseInt(y);

var theader = '<table>\n';
var tbody = "";

for(i= 1; i <= rX; i++){
tbody += '<tr>';

for (j = 1; j<= cY; j++){

tbody += '<td>';
tbody += i +':' +j;
tbody += '</td>';
}

tbody += '</tr>\n';
}

var tfooter = '</table>';

document.getElementById("table").innerHTML = theader + tbody + tfooter;}
</script>

Answer

You could add the new table to the last table in the output

document.getElementById("table").innerHTML += theader + tbody + tfooter;
//                                         ^

function createTable() {
  var x = document.getElementById("x").value;
  var y = document.getElementById("y").value;
  var rX = parseInt(x, 10); // add base
  var cY = parseInt(y, 10); // add base
  var theader = '<table>\n';
  var tbody = "";

  for (i = 1; i <= rX; i++) {
    tbody += '<tr>';
    for (j = 1; j <= cY; j++) {
      tbody += '<td>';
      tbody += i + ':' + j;
      tbody += '</td>';
    }
    tbody += '</tr>\n';
  }
  var tfooter = '</table>';
  document.getElementById("table").innerHTML += theader + tbody + tfooter;
}
<form>
  Row:
  <input type="text" id="x" />Columns:
  <input type="text" id="y" />
  <input type="button" value="OK" onclick='createTable();'></input>
</form>
<div id="table"></div>

Comments