Aaron Rotem Aaron Rotem - 4 months ago 10
Javascript Question

How to load data from a .txt file into a textarea

I am trying to fill a textarea with the data from a .txt file. I have tried using answers from similar questions but I can't find one that works.

In the head of the file I have this to import a library that is used with the jQuery:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>


Textarea declaration:

<textarea id="fillText" cols="40" rows="5"></textarea>


This is the script tag that I have right after the textarea declaration:

<script>
var fileName = '<?php echo $fileN;?>.txt'; //gets the filename
//The follow works and alerts the browser with the contents of the text file
jQuery.get(fileName, function(data) {
alert(data);
//process text file line by line
$('fillText').html(data.replace('n',''));

});
</script>


I have tried using this also:

$(".fillText").load(fileName);


But that does not work for some reason.

Answer

Since you are working with a textarea, you need to specify the value rather than the html.

Change:

$('fillText').html(data.replace('n',''));

To:

$('#fillText').val(data.replace('n',''));

Comments