Exploring a document using JavaScript

I am a beginner in JavaScript and I am attempting to read a file and display its contents on a browser.

Here is the code I have written so far:

<script type="text/javascript">
        var fname ;
        if(navigator.appName.search('Microsoft')>-1) { fname = new ActiveXObject('MSXML2.XMLHTTP'); }
        else { fname = new XMLHttpRequest(); }

        function read(filename) {
            fname.open('get', filename, true);
            fname.onreadystatechange= steady;
            fname.send(null);
        }

        function steady() {
            if(fname.readyState==4) {
                var el = document.getElementById('read_file');
                el.innerHTML = fname.responseText;
            }
        }
    </script>

However, the output I receive is:

x   y 5 90 25   30 45   50 65   55 85   25

While the data should be displayed in this format:

 x    y
 5    90
 25   30   
 45   50   
 65   55 
 85   25

I have two questions:

1) How can I display it in the desired format as shown above?

2) Currently, the file data is loaded when I click on a button. Is there a way to automatically read from the file without the need for clicking a button?

This is the HTML code snippet I have:

<input type="button" value="load file"  onclick="read('data.tsv')">

I would like to eliminate the "onclick" event and simply have the file read automatically.

Thank you

Answer №1

Is there a way to present the content in the same format as shown above?

To ensure proper formatting, make sure the container where you add the content has white-space: pre styling applied. Failure to do so may result in condensed spacing. Additionally, remember to escape special characters like <, >, ", and & when using innerHTML. Typically, <pre> elements are used for preserving spacing.

Currently, the display only happens upon clicking a button.. Can the system automatically read from the provided file without manual intervention?

If the <script> is executed after the #read_file element, you can directly call the function:

read('data.tsv');

If not, you can set an onload event handler that triggers once the page finishes loading:

window.onload = function () {
    read('data.tsv');
};

Answer №2

If you want to get rid of the button, simply include this JavaScript call at the end of your code:

    // ...

    loadData('data.tsv');
</script>

There are a few ways to showcase the data from the file exactly as it is.

One option is to encapsulate it in an element that maintains its white-space...

element.innerHTML = '<pre>' + responseData.responseText + '</pre>';

Another approach would be to replace all line breaks and spaces with HTML entities - for instance, turning a line break into a <br> tag and replacing a space with  .

You could also split the data by lines and spaces to present it in a table format, which would be the most suitable way to display the kind of information at hand.

Answer №3

To ensure proper formatting in the browser, be sure to use <br> instead of inserting a newline character directly.

Answer №4

To maintain the original format, consider using the <pre> tag. You can find more information here: http://www.w3schools.com/tags/tag_pre.asp

If you want your program to run without any user intervention, include

<body onload="read('data.tsv')">

Enjoy!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Internet Explorer Failing to Capture Blur Event (jQuery)

After doing a rapid search, I couldn't find an exact solution to this issue (I'm sure it has been addressed before), but I really need to get to the bottom of this... Does anyone have any insight into why this code snippet doesn't function ...

How to place a stylish font over an image and recreate hover effects

I am looking to place social media icons below an image next to the photo's title, including Facebook, Twitter, Soundcloud, and Instagram. I want these icons to rotate along with the image when it is hovered over. HTML <div class="polaroid-image ...

Different types of forms displayed together with a sole submission button in a separate section

https://i.sstatic.net/aAbD9.jpg My webpage consists of two main sections: the red section which is a partial view containing actions for forms, and the blue section which contains tabbed forms. Each tab in the blue section is also a view, called using the ...

The execution of Node.js callback function is not triggered

After setting up an API that queries a MongoDB and returns JSON Objects, I decided to modularize the code. I moved the MongoDB functionality to a separate file called queryMongo.js, which is now called in the POST request of main.js. Here is the main.js co ...

Determine the percentage of clicks on an HTML5 canvas radial progress bar

Recently, I designed a circular progress bar displaying a specific percentage. However, I am facing a challenge in determining how to calculate the percentage when a user clicks on either the black or green part of the circle. Could you provide insight on ...

Updating React props using useState?

Below is a component that aims to enable users to update the opening times of a store. The original opening times are passed as a prop, and state is created using these props for initial state. The goal is to use the new state for submitting changes, while ...

ASP/VB.NET Client-Side Script Generation/Registration

I am currently updating outdated "Web 1.0" code to align with modern standards. Is there a more efficient way to create and add a client-side script without having to concatenate numerous lines into a StringBuilder and then registering it to the page usin ...

An issue arises when request.body appears blank within the context of node.js, express, and body

I am currently attempting to send a request to my node server. Below is the xhttp request being made. let parcel = { userId: userId, //string unitid: unitid, //string selections: selections //array }; // Making a Call to the Server using XMLHttpR ...

Align images at the center of a division using the Bootstrap framework

I'm facing an issue with centering social network icons under a div in my login form while keeping it responsive. Can someone please assist me with this problem? Please help me!!. .row { background: #f8f9fa; margin-top: 20px; } .col { bor ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

error : failed to establish a connection to the MongoDB database

Ensure that the first parameter passed to mongoose.connect() or mongoose.createConnection() is a string. MongooseError: The uri parameter for openUri() must be a string, but it was "undefined". Double check that the initial parameter for mongoose.connect() ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

Was not able to capture the reaction from the Angular file upload

I've been attempting to upload a single file using the POST Method and REST Calling to the server. Despite successfully uploading the module with the code below, I encounter an error afterwards. Is there anyone who can lend assistance in troubleshooti ...

Tips on how to send Mongoose response variable in NodeJS Express router res.render?

I just finished setting up a basic Express NodeJS server. My goal is to save the value of the setting returned from mongoose.find() as a variable in res.render, but every time I try, it throws an error saying Cannot read property of undefined. Here' ...

Integrating Node.js with static HTML documents

I'm currently exploring methods for making node.js API calls from static HTML. While I've considered using Express and similar template engines, I am hesitant since they would require me to adjust my existing HTML to fit their templates. Typicall ...

Vue.js is having trouble locating images

I am currently using Vue-CLI with the latest version of Vue (3.9.3), but I am facing an issue where Vue cannot locate my images. Below are some screenshots for reference. Why are the images not showing up? First image (Structure) Second image (template) ...

Separating a variable within a Twitch bot: techniques and tips

I am working on setting up a feature in my Twitch bot where it can respond to the command !test [var]. For example, if someone types !test @jeff, the bot would reply with hello @jeff. Currently, I am using tmi. client.on('chat', function(channe ...

Verify whether the combobox has been chosen

Currently, I am dealing with two comboboxes and need to determine which one is selected. My intention is to achieve this using ajax and jquery within a JSP file. if(combobox1 is selected) { perform action 1 } if(combobox2 is selected) { perform actio ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

How does the Paginate Pipe effectively retrieve the array length in an Angular 2 application?

I find myself in an interesting situation where I have a piece of code that is functioning within my Angular 2 application - it's generating the correct value, but the method behind its success is unclear to me. Specifically, I am using ng2-paginatio ...