【问题标题】:JavaScript: Save HTML form and checkbox data to .txt file without server?JavaScript:在没有服务器的情况下将 HTML 表单和复选框数据保存到 .txt 文件?
【发布时间】:2019-10-26 08:39:04
【问题描述】:

我有一个带有文本和复选框输入的 HTML 表单,我想在提交表单时将此表单数据下载到文本文件中。

我将found a solution to download data from a textbox 写入一个文本文件,但我不知道如何修改它以获取我需要的其他文本和复选框输入。

这是我当前的代码:

<html>
    <head>
        <script language="Javascript">
            function download(filename, text) {
                var pom = document.createElement('a');
                pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
                    encodeURIComponent(Notes));
                pom.setAttribute('download', filename);
                pom.style.display = 'none';
                document.body.appendChild(pom);
                pom.click();
                document.body.removeChild(pom);
            }
            function addTextTXT() {
                document.addtext.name.value = document.addtext.name.value + ".txt"
            }
        </script>
    </head>
    <body>
        <form name="addtext" onsubmit="download(this['name'].value, this[’Notes’].value)">
            Notes:<input type="text" name=“Note/Users/karlahaiat/Desktop/Copia de checklist.htmls”><br>
            Initials:<input type="text" name=“Initials”><br>
            <input type="checkbox" name=“check_list[]” value=“Check General Health”>
            <b>Check General Health.</b><br>
            <input type="checkbox" name=“check_list[]” value=“Check Fluid”>
            <b>Check Fluid.</b><br>
            <input type="text" name="name" value="" placeholder="File Name">
            <input type="submit" onClick="addTexttxt();" value="Save As TXT">
        </form>
    </body>
</html>

上面的表格显示了我想要在我的表格中输入的字段,但是文本文件不会下载。任何理解语法的帮助都会很棒!

【问题讨论】:

  • 您希望值如何出现在文本字段中?您可能也想检查您的 HTML;它使用“印刷引号”(弯引号),这在 HTML 中无效。

标签: javascript html forms checkbox


【解决方案1】:

您的代码非常接近有效的解决方案 - 请考虑对您的代码进行以下更改(如下面的 sn-p 所示):

  • 避免在 HTML 标记中将 " 字符混合
  • 确保有效的字段名称并避免此表单的名称属性:name=“Note/Users/karlahaia..
  • 考虑使用addEventListener() 将事件逻辑绑定到您的HTML,而不是像您目前使用的那样使用内联onclickonsubmit
  • 另外,考虑在通过DOMContentLoaded 事件加载页面后设置表单逻辑。这可确保脚本所依赖的表单和输入元素在您的脚本尝试访问它们之前就已存在

/* Run script after DOMContentLoaded event to ensure form element is 
present */
document.addEventListener("DOMContentLoaded", function() {
  /* Obtain form element via querySelector */
  const form = document.querySelector('form[name="addtext"]');

  /* Bind listener to forms submit event */
  form.addEventListener("submit", function(event) {
    /* Prevent browsers default submit and page-reload behavior */
    event.preventDefault();

    /* Obtain values from each field in form */
    const notes = form.querySelector('input[name="notes"]').value;
    const initials = form.querySelector('input[name="initials"]').value;
    const checkFluid = form.querySelector('input[name="check-fluid"]').checked;
    const checkHealth = form.querySelector('input[name="check-health"]').checked;
    const filename = form.querySelector('input[name="name"]').value + ".txt";

    /* Compose text file content */
    const text = `
    notes:${notes}
    initials:${initials}
    check health (checkbox):${checkHealth}
    check fluid (checkbox):${checkFluid}
    `;

    /* Create temporary link element and trigger file download  */
    const link = document.createElement("a");
    const href = "data:text/plain;charset=utf-8," + encodeURIComponent(text);
    link.setAttribute("href", href);
    link.setAttribute("download", filename);

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
  });
});
<!-- Ensure that the name attribute does not include invalid characters 
or nested "" which cause confusion-->
<form name="addtext">
  Notes:<input type="text" name="notes" /><br /> Initials:

  <input type="text" name="initials" /><br />

  <input type="checkbox" name="check-health" value="Check General Health" />
  <b>Check General Health.</b><br />

  <input type="checkbox" name="check-fluid" value="Check Fluid" />
  <b>Check Fluid.</b><br />

  <input type="text" name="name" value="" placeholder="File Name" />
  <input type="submit" value="Save As TXT" />
</form>

希望有帮助!

【讨论】:

  • 太棒了!工作完美。感谢您提供语法提示。
【解决方案2】:

观察:

  1. 每个 HTML 5 有效文档都应该在开头提到一个 doctype,例如:&lt;!DOCTYPE html&gt;

2。您的方法很好,但是在 Firefox 中不推荐使用锚点上的 click() 方法。因此,我们必须在包含我们 TXT 文件的 URLEncoded 的隐藏锚点上手动调度 click 事件。

引自https://stackoverflow.com/a/1421770/8896148

click 方法旨在与类型为 INPUT 的元素一起使用 按钮、复选框、单选、重置或提交。 Gecko 没有实现 其他可能会响应的元素上的 click 方法 鼠标点击,例如链接(A 元素),也不一定会触发 其他元素的点击事件。

非 Gecko DOM 的行为可能不同。

  1. onClick="addTexttxt()" 中的函数名称拼写错误。这是addTextTXT()。 JavaScript 区分大小写!

  2. 与其直接调用download(filename, text) 函数,不如调用一个中间函数,它必须收集表单中的所有数据,并将其制成一个漂亮的文本字符串。然后,我们将该字符串传递给下载函数,使其成为可供下载的文件。

  3. onsubmit="someFunctionCall()" 中,如果我们不想离开页面(或重新加载),我们应该返回false。因此,我们通过在调用前面添加一个 return 来传递 someFunctionCall() 返回的值:onsubmit="return someFunctionCall()"。这样,我们可以在 someFunctionCall() 中通过返回 true 或 false 来决定是否要导航。

  4. 复选框和单选框的文本描述应放在&lt;label for="idOfTheInput"&gt; 内,这样用户可以点击文本,复选框仍会激活。

这是更新版本

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script language="Javascript" >

            function download(filename, text){

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

                pom.setAttribute('download', filename);
                pom.setAttribute('href', 'data:text/plain;charset=utf-8,'
                    + encodeURIComponent(text));

                pom.click();
                document.body.removeChild(pom);

            }

            //- SIDE NOTE for addTextTXT()
            //- This function works as it is, but it's a little sketchy using
            //- document.addtext directly inside it. The input we want to check
            //- should be passed as a parameter, if in the future we wish to
            //- extend this code to work with multiple forms in the same page.
            //- It's good for now, though
            
            function addTextTXT(){

                //- You may as well do some field validation here, and rename this
                //- function validate()

                //- Check if the last 4 characters of filename are already ".txt" or ".TXT"
                //- or any other variation of lower-case and upper-case
                if(document.addtext.filename.value.substr(-4).toLowerCase() != ".txt"){
                    //- Append ".txt" if missing
                    document.addtext.filename.value += ".txt"
                }
            }

            //- This function collects all the data present inside the form
            //- formats it accordingly, and passes the entyre text content
            //- to the download() function above
            function downloadData(formElement){

                //- We start with an initially empty file content
                var text = "";

                //- We iterate over all the form's inputs
                for(var i=0; i<formElement.length; i++){
                    var input = formElement[i];
                    //- We discard the submit button and the filename field.
                    //- If you remove this if statement the file will contain
                    //- all the inputs.
                    if(input.type == "text" && input.name != "filename"){
                        //- We append to the file content the name of the fiend
                        //- and it's value in single quotes (i like to quote them
                        //- to spot empty fields or to easily debug them later)
                        //- We append after each value an epty line: \n
                        text += input.name + "='" + input.value + "'\n";
                    }else if(input.type =="checkbox"){
                        text += "[" + (input.checked ? "x" : " ") + "] " + input.name + "\n";
                    }
                }

                //- Now the text variable contains all the info, so we send it
                //- for downloading
                download(formElement.filename, text);


                //- If we wish, we prevent navigation or page reload by returning false
                return false;
            }


        </script>
    </head>
    <body>

        <form name="addtext" onsubmit="return downloadData(this);">

            Notes:<input type="text" name=“Notes” value=""><br>
            Initials:<input type="text" name=“Initials” value=""><br>

            <input type="checkbox" name="Check General Health"> <b>Check General Health.</b><br>
            <input type="checkbox" name="Check Fluid"> <b>Check Fluid.</b><br>

            <input type="text" name="filename" placeholder="File Name">
            <input type="submit" onClick="addTextTXT();" value="Save As TXT">

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

【讨论】:

  • @AuxTaco 感谢您指出这一点!我已经更新了我的答案。
  • 感谢您的帮助!这两个答案都很好。我是一个初学者,所以我很感谢您的快速回复
猜你喜欢
  • 2018-03-24
  • 2013-05-28
  • 2014-06-18
  • 1970-01-01
  • 2011-08-28
  • 2019-08-11
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多