it_is_a_literature it_is_a_literature - 1 month ago 10
HTML Question

How to write the saveTable function?



function createTable(){
var _table = document.getElementById("test");
var newRow = _table.insertRow(1);
var cell0 = newRow.insertCell(0);
var cell1 = newRow.insertCell(1);
cell0.innerHTML = "x";
cell1.innerHTML = 60;
}

function saveTable(){
document.execCommand("saveas",,"/tmp/test.html");
}

<p>to create my table</p>
<input type="button" value="to create new table" onclick="createTable()" />
<input type="button" value="to save table as /tmp/test.html" oncilck="saveTable()" />
<table id="test" bodrder=1px>
<tr>
<td>f1</td>
<td>f2</td>
</tr>
</table>





when the table was created by function createTable,i want to get a file /tmp/test.html whose content is as following



<table id="test">
<tr>
<td>f1</td>
<td>f2</td>
</tr>
<tr>
<td>x</td>
<td>60</td>
</tr>
</table>





How to fulfil my saveTable function to do the job?

Answer

You could use a blob for this as explained here:

https://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

and here:

How to export source content within div to text/html file

<!DOCTYPE html>

<html>
<head>

 
  <title></title>
</head>

<body>
  <p>to create my table</p>

  <form>
    <input type="button" value="to create new table" onclick="createTable()"> <input type="button" value=
    "to save table as /tmp/test.html" onclick="saveTable()">
  </form>

  <table id="test" bodrder="1px">
    <tr>
      <td>f1</td>

      <td>f2</td>
    </tr>
  </table>
  
  
   <script>
function createTable() {
	var _table = document.getElementById("test");
	var newRow = _table.insertRow(1);
	var cell0 = newRow.insertCell(0);
	var cell1 = newRow.insertCell(1);
	cell0.innerHTML = "x";
	cell1.innerHTML = 60;
}

function saveTable() {
	var textToSave = document.getElementById("test").outerHTML;
	var textToSaveAsBlob = new Blob([textToSave], {
			type : "text/html"
		});
	var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
	var fileNameToSaveAs = "/tmp/test.html";

	var downloadLink = document.createElement("a");
	downloadLink.download = fileNameToSaveAs;
	downloadLink.innerHTML = "Download File";
	downloadLink.href = textToSaveAsURL;
	downloadLink.onclick = destroyClickedElement;
	downloadLink.style.display = "none";
	document.body.appendChild(downloadLink);

	downloadLink.click();
}

function destroyClickedElement(event) {
	document.body.removeChild(event.target);
}

  </script>

  
</body>
</html>