Can I save input from form to .txt in HTML, using

2019-01-14 18:43发布

问题:

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

回答1:

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.

<!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>
<script type="text/javascript">
<!--
// 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));
    });
});
//-->
</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>


回答2:

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



回答3:

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.



回答4:

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



回答5:

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>


回答6:

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>


回答7:

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:

<html>
<head>

<script language="Javascript" >
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"
}
</script>

</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>


回答8:

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>