我可以将输入从窗体到.txt在HTML中,使用JAVASCRIPT / jQuery,然后使用它吗? [英] Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?
问题描述
是否可以将textinput(本地)从表单保存到文本文件,然后打开该文档以供以后使用?
Is it possible to save textinput (locally) from a form to a textfile, and then open that document to use it later on?
只需使用HTML,javascript和jQuery。没有数据库或php。
Just using HTML, javascript and jQuery. No databases or php.
/ W
推荐答案
保存只有当用户允许它被保存就像一个下载,他必须手动打开它,唯一的问题是建议一个名称,我的示例代码将建议一个名称只为Google Chome,并且只有当你使用链接,而不是
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.
您只需要一个 base64编码库和JQuery,以方便操作。
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>
这篇关于我可以将输入从窗体到.txt在HTML中,使用JAVASCRIPT / jQuery,然后使用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!