What is the best way to handle reading and writing from a plain text file using JavaScript?

I am still learning about JS and it's a new world for me. I have a good understanding of HTML and CSS but recently, I was tasked with creating an application where I need to extract data from a plain text file and populate a form using JavaScript. Here is the content of my plain text file "data.txt":

Interfaces: test1,
IP: 192.168.1.1,
Mask : test,
Gateway : test,
DNS 1: test,
DNS 2: test,
Broadcast: test

Below is the structure of my form within a Div:

<div class="col-md-12">
            <div class="form-panel">
            <h4><i class="fa fa-angle-right"></i> Formulario </h4>
            <hr />
            <form method="post">
                <div class="form-group">
                    <label class="col-sm-3 col-sm-3 control-label">Interfaces:</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" 
                    </div>      
                </div>  
                 <div class="form-group ">
                    <label class="col-sm-3 col-sm-3 control-label">IP: </label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control"
                    </div>
                </div>
                 <div class="form-group">
                    <label class="col-sm-3 col-sm-3 control-label">Mask : </label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" 
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 col-sm-3 control-label"> Gateway : </label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" 
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 col-sm-3 control-label">DNS 1 : </label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" 
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 col-sm-3 control-label">DNS 2 : </label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" 
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-3 col-sm-3 control-label">Broadcast : </label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" 
                    </div>
                </div>
                <br><br>
                <div class="form-group">
                    <button type="submit" name="Save" class="btn btn-success btn-sm" " title="Save"><i class="fa fa-save"></i> Save</button>
                </div>
            </form>
        </div>

This is the script I obtained while searching for solutions.

The main goal is to display the content of "data.txt" in the form, allow users to modify fields, and save the changes back to the text file upon clicking the "Save" button. Is there a way to implement this successfully? Thank you!

Please find the complete code snippet below.

var mytext;
var connection = new XMLHttpRequest();
connection.open('GET', '/data.txt');
connection.onreadystatechange = function() {
mytext=connection.responseText;
}
connection.send();
<div class="col-md-12">
<div class="form-panel">
                <h4><i class="fa fa-angle-right"></i> Formulario </h4>
                <hr />
<form method="post">
<div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">Interfaces:</label>
                        <div class="col-sm-9">
<input type="text" class="form-control" 
                      </div>      
</div>
 <div class="form-group ">
<label class="col-sm-3 col-sm-3 control-label">IP: </label>
                        <div class="col-sm-9">
<input type="text" class="form-control"
</div>
                    </div>
 <div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">Mask : </label>
<div class="col-sm-9">
                        <input type="text" class="form-control" 
</div>
                    </div>
                    <div class="form-group">
<label class="col-sm-3 col-sm-3 control-label"> Gateway : </label>
<div class="col-sm-9">
                        <input type="text" class="form-control" 
</div>
                    </div>
                    <div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">DNS 1 : </label>
<div class="col-sm-9">
                        <input type="text" class="form-control" 
</div>
                    </div>
                    <div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">DNS 2 : </label>
<div class="col-sm-9">
                        <input type="text" class="form-control" 
</div>
                    </div>
                    <div class="form-group">
<label class="col-sm-3 col-sm-3 control-label">Broadcast : </label>
<div class="col-sm-9">
                        <input type="text" class="form-control" 
</div>
                    </div>
<br><br>
<div class="form-group">
<button type="submit" name="Save" class="btn btn-success btn-sm" " title="Save"><i class="fa fa-save"></i> Save</button>
</div>
</form>
</div>

</div>

Answer №1

Currently, I am not aware of a more efficient solution, but the code below is functional.

This is how I managed to accomplish it, utilizing jQuery .load()

$(document).ready(function(){
    // Load the file in a hidden div element.
    $("#hiddenFileLoad").load("data.txt", function(){
        // Callback runs when content is loaded

        // Store the content in a variable
        var loadedText = $("#hiddenFileLoad").text();
        console.log("loadedText:\n\n"+loadedText);

        // Split into an array
        var loadedTextSplitted = loadedText.split(",");

        // Remove the label part for each
        for (i=0;i<loadedTextSplitted.length;i++){
            temp = loadedTextSplitted[i].split(": ");
            loadedTextSplitted[i] = temp[1];
        }

        // Place each information in the HTML form
        $(".form-panel").find("input").each(function(index){
            $(this).val( loadedTextSplitted[index] );
        });

    }); // End of .load callback
});

I utilized a hidden div to load the content of the .txt file, assigning it the "hiddenFileLoad" id.

I did not make any alterations to your HTML (aside from adding the hidden div) and I used the content of your txt file.

I assume you are familiar with how to save to a file... I did not enable the save button functionality.

Here is a demonstration on my server.

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

5 Tips for Importing Internal CSS Conditionally Using JavaScript in Vue.js

At the moment, I am facing a challenge where I need to import a CSS file conditionally based on the user's browser. To keep the CSS file from being global, I have implemented the following code: created() { this.checkIsMobile() }, methods ...

"Troubleshooting: React Component Failing to Display Data Retrieved from API

Currently facing an issue in my React project where I am struggling to display fetched data from an API in my Movies component. Despite logging the data correctly in the console, it doesn't seem to show up on the page. Seeking assistance in identifyin ...

The special function for switching elements within arrays of arrays may yield unpredictable results at certain indexes

Having an Array of Arrays, my Array is named splitarr [Array2[], Array1[], Array0[], Array3[]...]. Unfortunately, it is not ordered correctly from Index Zero to index 2. Therefore, I am seeking a way to rearrange splitarr so that it follows this order => ...

Display or conceal features in a django application for users depending on their permission levels

I run a Django application where users log in to access its features. However, I need to restrict certain users from accessing specific parts of the web app. Even though I have tried using permission_required, the tab still displays in the HTML. Is there ...

Issue with Bootstrap 3 columns not arranging correctly

Utilizing Bootstrap 3, I am attempting to stack grids on top of each other in the order of A, B, C, D, E. While the mobile grid stacking works well, the issue arises when viewing it on desktop where the grids do not align as expected, particularly the box ...

How to discover a user's contacts on Telegram without knowing their username

As I work on developing a Telegram bot using Telegraf.js, one issue I've encountered is how to retrieve user contacts when the user doesn't have a username. The client for this project insists that the bot use some identifier to create a record i ...

Testing a function in Jest that utilizes the current date

I have a function that checks if the parameter date is the same as or later than today. In my function, I am using new Date() like this: import moment from "moment"; const validateDate = ({ date }) => { return moment(date, "DD-MM-YYYY").isSameOrAfte ...

`Is there a way to retrieve data from an array of Input elements using PHP?`

I am currently working on implementing a contact form using J Query, PHP AJAX. In the code snippet below, I am gathering form information and sending it to the server using a for loop and an array of form inputs. As someone who is new to this type of co ...

Can you specify the exact image name/path referenced in this CSS file?

I encountered a website that featured a copy image button. Upon inspecting the source code to locate the path or name of the PNG image used, I came across the following CSS. Can someone please help me identify where or what the path/name of the image is in ...

Reading out the timer in login credentials during entry can present an accessibility challenge under the Americans with Disabilities Act (

Scenario: The user is under a time limit of 15 seconds to enter their credentials, and has begun typing them in. Criteria: ADA users must be informed regularly about the remaining time and also be given permission to continue entering their credentials. ...

Rendering props conditionally in React

I am currently facing an issue with two different states retrieved from API calls: 'movieList' and 'search'. Both of them contain arrays of movies. The 'movieList' state is automatically rendered on the page to display popular ...

What is the best method for integrating static files (such as css, images, js, etc.) into our Node.js application?

Here is the structure of my project folder: XYZ_PROJECT_FOLDER ASSETS CSS IMAGES JS VENDOR CONTACT.html INDEX.html INDEX.js In the INDEX.js file, I have included code to render all the static files and routing logic: const e ...

The JavaScript function is not functioning properly when making an AJAX call

I am completely new to using ajax for the first time, so I am pretty clueless about it. I tried reading some articles on ajax, but unfortunately, they didn't help much. My goal here is simple - I just want to understand how ajax functions and what ste ...

Changing the title of a jQuery DataTable with a button click

Within my view, there are two input fields, a button, and a table that is utilizing jQuery DataTables. The datatable has a print functionality integrated into it. I am attempting to customize the title of the print page based on the values inputted into ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Paper.js - Applying transparency to shapes that extend beyond set boundaries

I am currently using a simple rectangle as the clipping area for all shapes added to the canvas, and it's working perfectly: var area = new paper.Rectangle( 100, 100, 300, 120 ); var path = new paper.Path.Rectangle(area); group.addChild(path); ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

D3 animation fails to refresh and stay current

After creating a page to visualize data using D3.js, everything seemed to be working fine on my desktop and when I debugged it on Chrome using device mode. However, I encountered an issue when trying to access the page on my iPhone - the SVG failed to upda ...

Using HtmlUnit in Java, you can easily open a hyperlink by referencing the <a href>

Within my HTML file, I have this specific section: <td> <a href="/romarin/detail.do?ID=0"> NAME </a> </td> Is there a way to access and open the link within the href attribute using HtmlUnit? This is the current code snippet I ha ...

Adding a variable to a URL using jQuery

Is there a way to add variable/text to the href attribute using jquery? ...