Reputation: 21
How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "@":
output=output.split("\n").filter(/./.test, /\@/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
Upvotes: 0
Views: 7071
Reputation: 4038
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\@/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Upvotes: 0
Reputation: 47099
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\@/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\@/.test(l); // Starting with @
return l.indexOf('@') > -1; // Containing @
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\@/.test.bind(/\@/)).join("\n");
The second arguments passed to the .filter
method is the context:
array.filter(callback[, thisObject])
Upvotes: 1