Can a text file be loaded into the title of a Bootstrap tooltip?

Looking to dynamically load a text file into bootstrap tooltip titles.

Here is a snippet of working code with hardcoded values:

<div>
    <a id="A" type="button" class="btn btn-outline-secondary btn-lg" data-toggle="tooltip" dataplacement="bottom" href="Some action"> A</a>
    <a id="B" type="button" class="btn btn-outline-secondary btn-lg" data-toggle="tooltip" dataplacement="bottom" href="Some action"> B</a>
    <a id="C" type="button" class="btn btn-outline-secondary btn-lg" data-toggle="tooltip" dataplacement="bottom" href="Some action"> C</a>
</div>

<script>
    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    });

    $('#A').tooltip({
        title: "June"
    });
    $('#B').tooltip({
        title: "July"
    });
    $('#C').tooltip({
        title: "August"
    });
</script>

I have a text file containing:

June
July
August

My goal is to update this text file using a script and dynamically assign these values to the tooltip titles.

I've tried using XMLHttpRequest() and $.get() methods but haven't achieved the desired result.

One attempt was:

function setTooltip(node) {
    $.get("My text File", function(responseText) {
        var Month = responseText;
    });
    console.log(Month);
    return Month;
}

$('#A').tooltip({
    title: setTooltip
});

The console logs the values correctly but the tooltip title remains empty.

Is there a better approach to achieve this? Or a way to iterate through the lines of the file?

Answer №1

With asynchronous ajax, your code may be injecting empty values before the call has returned. To fix this issue, try the following:

 $.get("My text File", function (responseText) {
        var Month = responseText;
        console.log(Month);
    }).done(function (Month) {
        console.log(Month);
        $('#A').tooltip({
            title: Month
        });
    });

If you need to split the results from the file structure you provided (one month per line), you can use the following code:

$.get("My text File", function (responseText) {
    let Months = responseText.split("\n");
    // Months is now an array -> ["June", "July", "August"]
}).done(function (Month) {
    console.log(Month);

    $('#A').tooltip({
        title: Month[0] // June
    });
    
    $('#B').tooltip({
        title: Month[1] // July
    });

    // Continue adding tooltips as needed ...
});

For future reference, consider retrieving data in JSON format instead of plain text for easier handling of multiple values.

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

What is the best way to create subpages within a survey?

If I want to create a survey page on the web with multiple questions, but I am facing a challenge. I do not want to have several different pages and use a "Next Button" that links to another page. I am struggling to come up with ideas on how to implement ...

Debugging Slideshows Using JavaScript

I am currently working on creating a slideshow and I'm facing some challenges with the JavaScript functionality. Everything seems to be running smoothly except for one issue - when I click right once, it transitions correctly, but if I then click left ...

Is there a way to shade the entire webpage background in HTML?

Instead of affecting other DOM classes, I tried using another div but it doesn't darken the whole page. This means I have to manually modify each DOM class. Is there a way to overlay the entire document with a semi-transparent gray plane? ...

Guide to adding the initial element in an array using Immutability Helpers

Looking to rearrange the elements in an array? The challenge is that it involves a link to the object. How can this be achieved using immutability helper? Below you will find my current code: state = { table: [['', '', ' ...

What is the best way to set the v-model property to an object that is constantly changing

I'm in the process of creating a dynamic form that allows users to add additional fields by simply clicking on a button labeled "adicionar condição." The concept is similar to what can be seen in the screenshot below: https://i.stack.imgur.com/Mpmr6 ...

Validating alpha-numeric passwords with JavaScript

I created a JavaScript function to validate if a password is alphanumeric. However, I am facing an issue where the alert message is not being displayed when the password is not alphanumeric. Below is my code snippet: if (!input_string.match(/^[0-9a-z]+$ ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...

Toggle the div if the if statement is true; otherwise, hide the broken

click: function(event, data) { $('#clicked-state') .text('You clicked: '+data.name); if (data.name == "VA") { $('#va').toggle(); } else { $('#va').style.d ...

Avoid re-running the onScroll function until completion

I have a unique idea for a slideshow where the slides fade in and out as the user scrolls up or down. The process involves detecting scroll movements and showing the next slide based on the direction of the scroll. The user scrolls using the scrollwheel ...

Please be patient for the PayPal script to load on the nextjs page

I've encountered an issue with my code that is meant to display PayPal buttons <Head> <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script> </Head> The PayPal buttons are loaded within the ...

Attempted to create registrations for two views using the identical name RCTScrollView

Having trouble running my React Native app on iOS, I keep getting an error while the Android version works perfectly fine. Does anyone have any insight on this issue? XCode 11.5, RN 0.61.5, Using React Native CLI I've searched multiple sites but hav ...

What is the method for retrieving an array or object that contains a collection of files designated for uploading within the jQuery file upload plugin?

Currently, I have successfully integrated a form into my Rails site and set up the jQuery file upload plugin. The upload form functions properly with the ability to select multiple files and utilize all ajax upload features. However, a challenge I am faci ...

Tips for incorporating images into an `.mdx` file located outside of the `public/` directory with the `next-mdx-remote` package in Next JS

I am currently developing a blog using next-mdx-remote and I am facing an issue with incorporating images in the .mdx file that are located outside of the public/ folder. If you would like to check out the complete code for my blog project, it is availabl ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

Read and manipulate website content using PHP

I recently encountered a challenging situation as a newcomer. Despite searching on Google, I couldn't find any information about it. There is a website that allows users to search for doctors in their area or state. It's possible that the number ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

Tips for positioning fixed column headers at the bottom of the header row

I am currently working on a responsive table where the first two columns are fixed and the rest are made to float. However, I have encountered some issues and have a few questions: Why do the headers for the first two columns float to the top of the head ...

Sending a document through the input field with React Hook Form

In my application, I have implemented a file input to submit a file and send it to a firebase storage bucket. To achieve this functionality, I am utilizing the react-hook-form library. However, I encountered an issue - I wanted the file to be uploaded with ...

Managing the state in NextJS applications

I've scoured the depths of the internet in search of a solution for this issue, but unfortunately I have yet to come across one that effectively resolves it. I've experimented with various state management tools including: useContext Redux Zusta ...