Home > database >  How to download an html webpage containing a filled form as an HTML file using javascript
How to download an html webpage containing a filled form as an HTML file using javascript

Time:06-05

I have a webpage that contains a form. The user will fill the fields form.

How can I save the webpage as an HTML file containing the filled fields?

The code below downloads the webpage as an HTML file but the fields are empty.

<a onClick="this.href='data:text/html;charset=UTF-8,' encodeURIComponent(document.documentElement.outerHTML)"
   href="#" download="page.html">Download</a>

CodePudding user response:

Please check the working codepen.io as the download feature does not work in Stackoverflow's snippet frame.

I just filled the "value" attribute for each input with its own value, then trigger the download.

function download(){
  var hiddenElement = document.createElement('a');
  var inputs = document.getElementsByTagName('input')
  for (var i = 0; i < inputs.length; i  )
    inputs[i].setAttribute("value", inputs[i].value);
  hiddenElement.href = 'data:attachment/text,'   encodeURI(document.getElementById("container").innerHTML);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'myFile.html';
  hiddenElement.click();
}
<div id="container">
<input value="" type="text">
<input value="" type="text">
<input value="" type="text">
<button onclick="download()">Download</button>
</div>

  • Related