如何在点击按钮时将这些文本字段(用户名和密码)下载到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>
答案 0 :(得分:0)
使用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
框