4

Here is my question,

I have a text file and I am reading the file using jquery.

the code is here

$(function() {
    $.get('files/james.txt', function(data) {
        $('.disease-details').html(data);
    }, 'text');
});

but I am getting only plain text and all formatting is disappearing.

I want to convert all the enter in to p tag. is it possible?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sujith Wayanad
  • 543
  • 6
  • 20

3 Answers3

5

You can do this :

$(function() {
     $.get('files/james.txt', function(data) {
        data = data.split("\n");
        var html;
        for (var i=0;i<data.length;i++) {
            html+='<p>'+data[i]+'</p>';
        }
        $('.disease-details').html(html);
    }, 'text');
});

The above splits up the text by new line (the text-"formatting") and wraps each chunk into a <p> .. </p> .. Exactly as requested.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
2

By definition, a plain-text file has no formatting to begin with (hence the "plain" part).

If you mean newline characters, those are not rendered in HTML by default. To overcome this, you can simply wrap your text with a <pre> tag which among other things is rendered including newline characters.

For example:

$(function() {
    $.get('files/james.txt', function(data) {
        $('.disease-details').html($('<pre>').text(data)); // Text wrapped in <pre>
    }, 'text');
});
Boaz
  • 19,892
  • 8
  • 62
  • 70
  • my text is not html text. I have only text with 3 paragraph it is separated with only enter – Sujith Wayanad Oct 16 '13 at 10:25
  • When you press the "Enter" key, you're actually inserting a newline character in to the text file. The browser does not show these characters, unless you're using the `pre` tag. Note the difference in `html($('pre').text(data))`. – Boaz Oct 16 '13 at 10:26
0

You will either have to get the file pre-formatted using HTML tags / or just get the data from the text file and do a client side formatting ( using templates or otherwise ). Can give you better pointers if you give sample of what the data in the file would look like

sreekarun
  • 167
  • 3