[javascript] Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Is it possible to save textinput (locally) from a form to a textfile, and then open that document to use it later on?

Just using HTML, javascript and jQuery. No databases or php.

/W

This question is related to javascript jquery html css xhtml

The answer is


BEST solution if you ask me is this. This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.

Example:

_x000D_
_x000D_
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}

function addTextHTML()
{
    document.addtext.name.value = document.addtext.name.value + ".html"
}

function addTextTXT()
{
    document.addtext.name.value = document.addtext.name.value + ".txt"
}
_x000D_
<html>
  <head></head>
  <body>

    <form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">

    <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
    <br>
    <input type="text" name="name" value="" placeholder="File Name">
    <input type="submit" onClick="addTextHTML();" value="Save As HTML">
    <input type="submit" onClick="addTexttxt();" value="Save As TXT">

    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_


It's possible to save only if the user allow it to be saved just like a download and he must open it manually, the only issue is to suggest a name, my sample code will suggest a name only for Google Chome and only if you use a link instead of button because of the download attribute.

You will only need a base64 encode library and JQuery to easy things.

_x000D_
_x000D_
// This will generate the text file content based on the form data
function buildData(){
  var txtData = "Name: "+$("#nameField").val()+
      "\r\nLast Name: "+$("#lastNameField").val()+
      "\r\nGender: "+($("#genderMale").is(":checked")?"Male":"Female");

  return txtData;
}
// This will be executed when the document is ready
$(function(){
  // This will act when the submit BUTTON is clicked
  $("#formToSave").submit(function(event){
    event.preventDefault();
    var txtData = buildData();
    window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
  });

  // This will act when the submit LINK is clicked
  $("#submitLink").click(function(event){
    var txtData = buildData();
    $(this).attr('download','sugguestedName.txt')
      .attr('href',"data:application/octet-stream;base64,"+Base64.encode(txtData));
  });
});
_x000D_
<!DOCTYPE html>
<html>
    <head><title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="base64.js"></script>
    </head>
    <body>
    <form method="post" action="" id="formToSave">
        <dl>
            <dt>Name:</dt>
            <dd><input type="text" id="nameField" value="Sample" /></dd>
            <dt>Last Name:</dt>
            <dd><input type="text" id="lastNameField" value="Last Name" /></dd>
            <dt>Gender:</dt>
            <dd><input type="radio" checked="checked" name="gender" value="M" id="genderMale" />
                Male
                <input type="radio" checked="checked" name="gender" value="F" />
                Female
        </dl>
        <p><a href="javascript://Save as TXT" id="submitLink">Save as TXT</a></p>
        <p><button type="submit"><img src="http://www.suttonrunners.org/images/save_icon.gif" alt=""/> Save as TXT</button></p>
    </form>
    </body>
</html>
_x000D_
_x000D_
_x000D_


Or this will work too the same way but without a save as choice:

<!DOCTYPE html>
<html>
<head>


<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
  };


  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();

}//]]> 

</script>


</head>

<body>
  <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>


  <script>
  // tell the embed parent frame the height of the content
  if (window.parent && window.parent.parent){
    window.parent.parent.postMessage(["resultsFrame", {
      height: document.body.getBoundingClientRect().height,
      slug: "qm5AG"
    }], "*")
  }
</script>

</body>

</html>

From what I understand, You have to save a user's input locally to a text file.

Check this link. See if this helps.

Saving user input to a text file locally


You can use localStorage to save the data for later use, but you can not save to a file using JavaScript (in the browser).

To be comprehensive: You can not store something into a file using JavaScript in the Browser, but using HTML5, you can read files.


Answer is YES

<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>

<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>  
</form> 

</body>
</html>

You cannot save it as local file without using server side logic. But if that fits your needs, you could look at local storage of html5 or us a javascript plugin as jStorage


This will work to both load and save a file into TXT from a HTML page with a save as choice

<html>
<body>

<table>
    <tr><td>Text to Save:</td></tr>
    <tr>
        <td colspan="3">
            <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
        </td>
    </tr>
    <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
    <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </tr>
</table>

<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    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);
}

function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

</script>

</body>
</html>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to xhtml

How to refresh table contents in div using jquery/ajax Uses for the '&quot;' entity in HTML The entity name must immediately follow the '&' in the entity reference Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it? How to vertically align a html radio button to it's label? Image height and width not working? Removing border from table cells Enable & Disable a Div and its elements in Javascript how to remove the bold from a headline? How to make div occupy remaining height?