javascript - 单击按钮时,如何将这些文本字段下载到 txt 文件中?
问题描述
单击按钮时,如何将这些文本字段(用户名和密码)下载到 txt 文件中?(它只是用于前端学校项目)。我知道这不是正常做法,但我只需要演示一个前端产品。
我的代码....
<h3>Login</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Username:</label>
<input type="text" class="form-control" id="name">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Password:</label>
<input type="password" class="form-control" id="password" required data-validation-required-message="Incorrect username or password.">
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Login</button>
</form>
</div>
这是一个示例中的代码,可以满足我的要求,但我无法应用该代码来使我的表单工作......
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<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);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=1 cols=25 name="text"></textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById ('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById ('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
<input type="submit" value="SAVE">
</form>
</body>
</html>
解决方案
使用 js 生成和下载文本文件的示例代码 -
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=1 cols=25 name="text"></textarea>
<input type="submit" value="SAVE">
</form>
</body>
</html>
代码参考
上面的代码将下载名称写在第一个框中的文件和第二个框中text
的文件数据textarea
推荐阅读
- python - 为什么 GPS 时间和日期之间存在差异
- google-cloud-platform - 对 ory hydra / Google 身份平台感到困惑
- javascript - 为什么总是重绘整个画布?
- python - Python在一个类中实现链表
- docker - 我可以在 docker build 期间避免或缓存 `usermod` 和 `chown` 命令吗?
- kubernetes - 监控 k8s pod 的 tcp 连接数
- python - 如何让我的 selenium 代码运行得更快?
- javascript - 销毁并重新初始化引导滑块
- java - 杰克逊:@JsonUnwrapped 自定义字段名称和自定义反序列化模块时无法识别的字段
- amazon-web-services - 是否可以在 AWS 中自动创建 AMI?