3

i have an array called items=["apple","mango","cherry"];

i wonder how i can load the array data from text file instead of declaring it?the text file data is stored like this "apple","mango","cherry",...

furthermore, how to add to the end of this this text file an item for example add "orange" after "cherry"?

items=["apple","mango","cherry"];
    if (items.indexOf(myVariable2) == -1) {

     // not found, so output it
       t++;

    document.myform3.outputtext3.value +=myVariable2+"\n";

    }
user1788736
  • 2,727
  • 20
  • 66
  • 110
  • 2
    Where is your text file stored? – Lee Taylor Jul 27 '13 at 19:34
  • So is text file local or on a server? Your question is missing this important part... – A. Wolff Jul 27 '13 at 19:39
  • First If it is possible, store your data as JSON. Then, follow [this](http://stackoverflow.com/a/8951858/1725764) to load the file content and parse it to JSON. [jQuery Reference](http://api.jquery.com/jQuery.getJSON/). – Hashem Qolami Jul 27 '13 at 19:41

3 Answers3

5

With jQuery you can do something like this

  $.get("textFile.txt", function(data) {
      var items = data.split(',');
  });

You may need something like this though

var items = data.replace(/"/g, '').split(',');

This is a start.

If this is a user input file then you may need to upload it before you work with it.

iConnor
  • 19,997
  • 14
  • 62
  • 97
  • you have to use regex with replace() or only first occurence will be replaced – A. Wolff Jul 27 '13 at 19:41
  • connor this script is only run by me i just want to do away to make life easier for myself instead of typing new data to end array manually!i was just looking for way to read and write from txt file . may be i load data from textarea instead but don't know how ! – user1788736 Jul 27 '13 at 20:04
  • Well, from what you just said, this looks like what you need – iConnor Jul 27 '13 at 20:06
4

Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.

But one way to access the text file using jQuery would be

jQuery.get('http://localhost/foo.txt', function(data) {
    var myvar = data;
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shiva
  • 6,677
  • 4
  • 36
  • 61
  • 1
    thanks for reply. so you think it is not possible to load from txt file ? how about loading from cookie file or textarea? myvar can be used outside jquery.get ?how? – user1788736 Jul 27 '13 at 19:41
  • @user1788736 simply declare the variable before the .get, and inside the get, instead of using 'var myvar', use 'myvar' – DrunkWolf Sep 14 '15 at 09:17
0
 var file = event.target.file;
 var reader = new FileReader();
 var txt=reader.readAsText(file);
 var items=txt.split(",");