user3063909
user3063909

Reputation: 383

Import txt file into Modal body

I have the file Contact.txt imported in my project with the

id='contact'

The uploading part I do with the following function:

var loadFile = function ('./data/en/Contact.txt', 'contact', true) {
    var allText;
    var titleText;

    var txtFile = new XMLHttpRequest();
    txtFile.open("GET", source, true);

    txtFile.onload = function () {
        if (txtFile.readyState === txtFile.DONE) {
            if (txtFile.status === 200) {
                allText = txtFile.responseText.split('\n');
                if (hasOnlyTitle == false) {
                    //selects the first line from the txt file, in our case the title
                    titleText = allText[0];

                    //removes the first line from txt file
                    allText.splice(0, 1).join('\n');
                    document.getElementById(targetId + "Title").innerHTML = titleText;
                }
                var finalText = allText.join('<br />');
            }
            document.getElementById(targetId).innerHTML = finalText;
        }
    };
    txtFile.send(null);
}

The uploading function I have tested separated and it works...

I have tried to import the text from the file into the body of a modal component, but it just won't display anything...

Here is the html part:

            <div id="myModal" class="modal">

                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close">&times;</span>
                    <p id="contact"></p>
                </div>
            </div>

And this is the js file:

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("info");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function () {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function () {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

Upvotes: 1

Views: 1061

Answers (1)

user7062061
user7062061

Reputation:

On your code you never load the content of the file. Assuming that you have the file on the server, you can load the content when the page is open adding something like this to the jquery document ready:

$.get('/contact.txt', function(data) {
    $("#contact").text(data)
});

or use the same function inside the btn.onclick. This will be slower, and the information can take some time to load. So it's better to load the information on document load/ready.

This way, when the users open's the modal, the contact information will be quickly available.

Upvotes: 2

Related Questions