2016-10-23 3 views
1

私は「エクスポート」ボタンをクリックすることで、テキスト領域から出力をダウンロードできるようにするためのスクリプト(ヘルプを保存するように促す)を探しています。私は答えに得ている出力をtxtファイルとしてダウンロードするようにユーザに促す

<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="OUTPUT"> 
</textarea> 

最も近い下のこのですが、明らかにそれは私の出力を使用しない、ファイルを作成しています:

var a = window.document.createElement('a'); 
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'})); 
a.download = 'test.csv'; 

// Append anchor to body. 
document.body.appendChild(a) 
a.click(); 

// Remove anchor from body 
document.body.removeChild(a) 

すべてのヘルプはが大幅いただければ幸いです。

+1

チェックこのブログの記事http://cwestblog.com/2014/10/21/javascript-creating-a-downloadable-file-ブラウザで/あなたを途中で取得します。 – Jim

+0

[Javascriptのみを使用したファイルとしてテキストエリアのコンテンツをダウンロードする(サーバー側なし)](http://stackoverflow.com/questions/609530/download-textarea-contents-as-a-file-using-only- javascript-no-server-side) – repzero

答えて

0

メソッドを使用すると、textareaの値をcreateObjectURL関数に渡すだけです。

<textarea id="output" class="form-control text-box noresize" rows="4" placeholder="This text will be downloaded as a file."> 
</textarea> 

<br> 
<button id="download">Download</button> 

<script> 
document.getElementById('download').addEventListener("click", download); 

function download(){ 
    var text = document.getElementById('output'); 
    var a = window.document.createElement('a'); 
    a.href = window.URL.createObjectURL(new Blob([text.value], {type: 'text/plain'})); 
    a.download = 'test.txt'; 

    document.body.appendChild(a) 
    a.click(); 
    document.body.removeChild(a) 
} 
</script> 
0

これを試してみてください:

var txt = document.getElementById('content').value; 
 

 
document.getElementById('link').onclick = function(){ 
 
    this.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt); 
 
}; 
 

 
document.getElementById('content').onchange = function(){ 
 
    txt = document.getElementById('content').value; 
 
};
<body> 
 

 
    <div> 
 
\t <textarea id="content">Hello World</textarea> 
 
    </div> 
 

 
    <a href="" id="link" download="content.txt">Download</a> 
 
    
 
</body>

関連する問題