How can you extract information from a text document and seamlessly incorporate it into an HTML webpage?

I am currently working with an HTML file structured like this..

<html>
<body>
<table border="1" cellpadding="5">
<tr>
<td>Some Fixed text here</td>
<td id="data">---here data as per values in external text file---</td>
</tr>
</table>
</html>

Within the same directory, I have a text file called data.txt alongside the index.html file.

My goal is to use scripts to read the text file and place specific innerHTML content in the id=data based on the values in the first character of the text file.

For example,

for 0 in the first character, innerHTML=

<div style="color:red; border:2px dotted blue;">Alpha</div>

for 1 in the first character, innerHTML=<div>Beta</div>

for 2 in the first character, innerHTML=

<div>Gamma<span>more text</span></div>

and so on...

I have attempted to implement various scripts using jQuery and AJAX, but they have not provided the desired results. Due to my limited knowledge of these technologies, I am struggling to identify the issue. Is there anyone who can assist me in creating a script using JavaScript or a similar language?

Answer №1

Here's a jQuery solution to check the first character of a plain text file:

$( function(){
    $.ajax({
        url: 'data.txt',
        type: 'get',
        success: function(data) {
            if (data.substr(0,1) == 0)
                {$("#data").html('<div style="color:red; border:2px dotted blue;">Alpha</div>');}
            if (data.substr(0,1) == 1)
                {$("#data").html('<div>Beta</div>');}
        },
    });
});

You can include additional conditions as needed for your specific requirements.

Note:

Ensure to include the jQuery library in your HTML document when using jQuery code:

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

Answer №2

Read and save the content to a variable in JavaScript :

var content = new XMLHttpRequest();
content.open('GET', '/data.txt');
content.onreadystatechange = function() {
  alert(content.responseText);
}
content.send();

Alternatively, embed the content directly into the page using PHP (an easier option in my opinion) :

<div><p><?php include('data.txt'); ?></p></div>

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

refresh the page and submit a post to his own profile

I am working on a PHP page with the code $id=$_GET['id'];. I am trying to create a dropdown menu that, when an option is selected, will reload the page with the GET method plus a new value as a parameter. This is what I have done so far: functi ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

Deleting list items by clicking a button

I'm working on adding a functional "x" button to each list item (li) so that users can click on it to remove the item. I've successfully added the button, but I'm unsure about what code to use in the onClick event to delete the corresponding ...

Enliven the transition between grid sizes

I'm currently working on a project using React and Material UI. Seeking assistance on how to implement an animation for changing the size of a grid item. By default, the item is set to sm={3}, but when a user hovers over it, I want it to change to sm ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Decline the input according to the percentage

After experimenting with the script, I discovered that it did not perform as expected (even though it works on Google Webapp's script HTML form). My goal is to invalidate an input if the Downpayment is less than 30% or more than 100% of the Price, in ...

SVG Opacity Transitions seem to ignore the constraints of CSS rules and bounce chaotically beyond their designated boundaries

I'm currently working on implementing a hover effect for an SVG rect embedded in HTML. The transition I've set up is not smooth, and the opacity values seem to be inconsistent during the animation. My browser of choice is Firefox. The rect I&apo ...

Finding the element in the HTML using selenium and Python

Recently, I have been working on automated testing using Selenium. However, I have encountered a strange issue where I am unable to locate the element. Can someone please provide me with guidance on how to handle this situation? driver.find_element_by_xpa ...

Sending state information through props in a Vuex environment

One of the challenges I am facing is how to make a reusable component that can display data from the store. My idea is to pass the name of the store module and property name through props, as shown below: <thingy module="module1" section=" ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

Retrieve an element within a jQuery each loop

I'm currently implementing AJAX functionality to retrieve cart items from the server and display them within a cart when a customer clicks on the "My Cart" button. Here is the model for the cart: public class Cart { [Key] public i ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...

Transform js into a more dynamic format to avoid redundancy when displaying items upon click

I came across a simple lightbox code snippet, but it's based on IDs and I plan to use it for more than 20 items. I don't want to manually write out 20 JavaScript lines when there could be a more efficient way to handle it dynamically. My JS skill ...

What purpose does the "io" cookie serve in Socket.IO?

Can someone explain the purpose of Socket.IO using the io cookie as a session cookie? I understand that it can be disabled, but I couldn't find any information on it in the documentation. Why is it turned on by default and what consequences would ther ...

Display a tooltip when the cursor hovers close to a line in D3 visualizations

Currently, I have a D3js line chart with SVG circles added to the points. When users hover over these circles, they can see a tooltip. https://i.sstatic.net/kYpeg.png https://jsfiddle.net/jhynag08/38/ However, I would like the tooltip to appear when user ...

How can we export data to excel using react-export-excel while ensuring certain columns are hidden?

Greetings! I believe the title gives you a clear idea of my dilemma. When exporting data, there are no errors - my goal is to hide the Excel column when the checkbox is unchecked or false, and display it when the checkbox is checked or true during export. ...

Using PHPMailer and AJAX to attach a file to an email

I successfully implemented a contact form on my website that allows users to send emails without refreshing the page, thanks to Ajax. Now, I want to add a feature where users can attach files to their emails, but I'm struggling with processing this d ...

Tips for fashionable dressing &

Can you provide some insights on how to format the &amp; symbol in this HTML snippet? <a>Ian</a> &amp; <a>Jim</a> ...

What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue. UsersPage.vue: <script> export default { data:() =>({ usersList : [] }), methods:{ async createUsersList(){ this.usersLi ...

Unable to transmit Props to Component - Fluctuating Behavior

I developed a React.js and Next.js application where I needed to pass the User object to all pages. My plan was to then pass this User component to the Head component in order to display different navigation options based on the user's role. Here is w ...