1

I get an error like this.

ReferenceError: newtableHTML is not defined

  let initialTable = [];
  initialTable.push({
    table: newtableHTML
  });

This made me unable to access the elements, and I had to reload the page so the code could work. I just know when opening the console and it turns newtableHTML not defined.

how to be able to call it outside the submitButton function?

jQuery :

$('.submitButton').click(function() {
  function getTableList() {
    var addTable = /*htmlcode*/ ;
    return addTable;
  }
  if ( /* code */ ) {
    // some code
  } else {
    var resultTable = JSON.parse(localStorage.getItem("tableList"));
    if (resultTable == null) {
      resultTable = [];
    }
    var newtableHTML = getTableList();
    resultTable.push({
      table: newtableHTML
    });
    localStorage.setItem("tableList", JSON.stringify(resultTable));
    $('.tab-content').append(newtableHTML);
    var newTable = $("#table" + localStorage.Index).dataTable();
  }
}); // submitButton function

var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {


  for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
  }
  $(".dynamicTable").dataTable();
} else {
  let initialTable = [];
  initialTable.push({
    table: newtableHTML
  });
  localStorage.setItem("tableList", JSON.stringify(initialTable));
}

Previously, var newtableHTML is let newtableHTML.

Then I changed it to var newtableHTML but no luck.

Calvin Ananda
  • 1,440
  • 1
  • 14
  • 30

1 Answers1

1

This is because you have declared var newtableHTML inside the $('.submitButton').click(function() and trying to access it outside of it.

You have to declare- newtableHTML outside of $('.submitButton').click(function() or globally so that it is accessible.

Try something like this-

var newtableHTML; //declare it here
$('.submitButton').click(function() {
  function getTableList() {
    var addTable = /*htmlcode*/ ;
    return addTable;
  }
  if ( /* code */ ) {
    // some code
  } else {
    var resultTable = JSON.parse(localStorage.getItem("tableList"));
    if (resultTable == null) {
      resultTable = [];
    }
    newtableHTML = getTableList();  //initialize it here
Souvik Ghosh
  • 4,456
  • 13
  • 56
  • 78