[英]How do I get these text fields to download into txt file when button clicked?
單擊按鈕后,如何將這些文本字段(用戶名和密碼)下載到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
框中的文件數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.