10

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.

<html>
   <head>
      <title>textbox</title>
      <script type="text/javascript">
         function readBOX() {
            var txtinput = document.getElementById('txtinput').value;
            document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
         }
      </script>
   </head>
   <body>
      <p> Type</p>
      <input type="text" id="txtinput" />
      <input id="open" type="button" value="READ" onClick="readBOX()" />
      <form>
         <textarea name="text" rows="20" cols="70">loaded text here</textarea>
      </form>
   </body>
</html>
Martin
  • 3,096
  • 1
  • 26
  • 46
Gwa Si
  • 335
  • 1
  • 3
  • 13

5 Answers5

11

You have to use something like its posted in this Answer

jQuery

$(document).ready(function() {
   $("#open").click(function() {
       $.ajax({
           url : "helloworld.txt",
           dataType: "text",
           success : function (data) {
               $("#text").text(data);
           }
       });
   });
}); 

Read more on the jQuery Documentation of .ajax()

Non jQuery

I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:

var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;

But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia

Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object

Community
  • 1
  • 1
Martin
  • 3,096
  • 1
  • 26
  • 46
  • Please do not downvote without comment. Additional information about fileaccess from JS can be found on [this page](http://stackoverflow.com/questions/371875/local-file-access-with-javascript) – Martin Sep 26 '13 at 06:08
  • 6
    I downvote people who answer with jQuery when the asker wasn't using jQuery. It's true he needs to look into ajax, but I dislike suggesting jQuery solely for that. – Joe Simmons Sep 26 '13 at 06:10
  • 1
    Then write in you question that you do not want to use jQuery. I think the jQuery way is the most common and the first approach. – Martin Sep 26 '13 at 06:12
  • 8
    I disagree. I think jQuery is only acceptable if you're already using it, or planning to. And I think you should only recommend it when you know the asker is using it. – Joe Simmons Sep 26 '13 at 06:16
  • @JoeSimmons - I have added some non-jquery way of doing this. we need not to discuss. The user had a question and do not want to include jQuery ;) – Martin Sep 26 '13 at 06:22
  • Ok. I switched it to a thumbs up :) – Joe Simmons Sep 26 '13 at 06:25
  • suggest to use $("#text").text(data); instead in your jQuery based solution for placing value in textarea – Ahsan Shah Sep 26 '13 at 06:42
  • can i change that url to ("http://mywebsite.com/textfile/") + txtinput +(".txt")? – Gwa Si Sep 29 '13 at 22:34
  • I think this will work if your source website hosted on the same domain – Martin Sep 30 '13 at 05:51
  • I can't take off this. I need to use it. ("http://mywebsite.com/textfile/") + txtinput +(".txt") – Gwa Si Oct 05 '13 at 13:03
  • 2
    using $("#text").val(data) instead of $("#text").text(data) has the advanatge that the text is set even if the user already modified the text in the textarea. – Reto Gmür Jun 24 '15 at 15:11
4

Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.

<!DOCTYPE HTML>
<html>
   <head>
      <title>textbox</title>
   </head>
   <body>
<form action="process.php" method="post">
      <input type="text" name="name" />
      <input type="submit" />
</form>
   </body>
</html>

Process.php

<textarea name="text" rows="20" cols="70"> 
<?php $name =  $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
Gwa Si
  • 335
  • 1
  • 3
  • 13
3

This is how I load text into a textarea

Main.css

.textbox{
         font-size: 12px;
         float  : left;
         height : 197px;
         width : 650px; }


Default.html

<!DOCTYPE html>
<html> 
    <head>
        <!-- Charactor set allowed to use -->
        <meta charset="utf-8"/>

        <title>Text from .txt file to TextArea</title>

        <!-- External stylesheet -->
        <link rel="stylesheet" href="main.css" />

        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    </head>
    <body>
       <textarea class="textbox" id="Brief" readonly></textarea>

       <script> $( "#Brief" ).load( "text.txt" ); </script>
    </body> 
</html>

google textarea to find format of text area

1

One of the easiest way is to request the server to return the pre-filled textarea (Here's an example using PHP):

<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>

Note: Something similar can be done with any server-side scripting language.

In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.

Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):

Pure JS:

if (typeof XMLHttpRequest === "undefined") {
    XMLHttpRequest = function () {
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
        catch (e) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
        catch (e) {}
        try { return new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (e) {}
        throw new Error("This browser does not support XMLHttpRequest.");
    };
}

function readBOX() {
    function reqListener () {
        document.forms[0].text.value = this.responseText;
    }

    var txtinput = document.getElementById("txtinput").value;
    var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";

    var oReq = new XMLHttpRequest();
    oReq.onload = reqListener;
    oReq.open("get", filePath, true);
    oReq.send();
}

But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:

jQuery:

function readBOX() {
    var txtinput = document.getElementById("txtinput").value;
    var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";

    $.ajax({
        url: filePath
    }).done(function(data){
        document.forms[0].text.value = data;
    });
}

Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.

Hope this helps :)

Frederik.L
  • 5,522
  • 2
  • 29
  • 41
  • Do we still have to go through `ActiveXObject` hell? Aren't all modern browser support `XMLHttpRequest`? – Pavlo Sep 26 '13 at 08:07
  • For older IE versions on XP and prior, I'm afraid so. On modern browsers that is not any concern. – Frederik.L Sep 26 '13 at 15:39
0
window.addEventListener('DOMContentLoaded', (e) => {
    let input = document.getElementById('input');
    
    // load default.txt into input box
    try {
        let fileToLoad = './default.txt';
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open('GET', fileToLoad, false);
        xmlhttp.send();
        input.innerHTML = xmlhttp.responseText;
    } catch(DOMException) {
        input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
    }
});
RedDragonWebDesign
  • 1,797
  • 2
  • 18
  • 24