Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving HTML5 textarea contents to file

Could someone help me save the contents of a HTML5 textArea to file, preferably using JavaScript?

<textarea id="textArea">
   Notes here...
</textarea>
<button type="button" value="save"> Save</button>
like image 983
FootsieNG Avatar asked Jan 31 '14 11:01

FootsieNG


People also ask

How do I display textarea content in HTML?

Use the <textarea> tag to show a text area. The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows. Specifies that on page load the text area should automatically get focus.

Is textarea available in HTML5?

HTML5 introduced a few new attributes which can be used with textarea elements. Here are some of the most important: form : Associates the textarea with a form. Use the ID attribute of the form as the value for the textarea form attributes.

Does textarea have to be in form?

Yes, you can use textarea outside of form; there is no problem in it.


1 Answers

That should do it.

function saveTextAsFile() {
  var textToWrite = document.getElementById('textArea').innerHTML;
  var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
  var fileNameToSaveAs = "file.txt"; //filename.extension

  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "Download File";
  if (window.webkitURL != null) {
    // Chrome allows the link to be clicked without actually adding it to the DOM.
    downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
  } else {
    // Firefox requires the link to be added to the DOM before it can be clicked.
    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
  }

  downloadLink.click();
}

var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);

function destroyClickedElement(event) {
  // remove the link from the DOM
  document.body.removeChild(event.target);
}
#textArea {
  display: block;
  width: 100%;
}
<textarea id="textArea" rows="3">
   Notes here...
</textarea>
<button type="button" value="save" id="save">Save</button>

JSFiddle

like image 142
engincancan Avatar answered Oct 11 '22 14:10

engincancan