JavaScript:无需服务器即可将HTML表单和复选框数据保存到.txt文件?

时间:2019-06-11 21:30:47

标签: javascript html forms checkbox

我有一个带有文本和复选框输入的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>

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

2 个答案:

答案 0 :(得分:1)

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

  • 避免在HTML标记中将"字符混合在一起
  • 确保有效的字段名称,并避免使用以下形式的name属性: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>

希望有帮助!

答案 1 :(得分:0)

观察

  1. 每个HTML 5有效文档在开始时都应具有一个doctype,例如:<!DOCTYPE html>

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

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

  

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

     

非壁虎DOM的行为可能有所不同。

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

  2. 我们应该直接调用中间函数,而不是直接调用download(filename, text)函数,该函数必须从表单中收集所有数据,并将其转换为漂亮的文本字符串。然后,我们将该字符串传递给download函数,以使其成为可下载的文件。

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

  4. 复选框和广播的文本说明应放在<label for="idOfTheInput">内,以便用户可以单击文本,并且复选框仍将激活。

这是更新的版本

<!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 itterate through 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>