Freshening up the data source in a Bootstrap Typeahead using JavaScript

I'm trying to create a dropdown menu that displays options from an array stored in a file called companyinfo.js, which I retrieve using ajax. The dropDownList() function is called when the page loads.

function dropDownList (evt) {
    console.log("dropdownfired");
    var companyArray = [];
    $.ajax({
        url : 'assets/data/companyarray.js', //this file contains ["Facbeook", "Twitter", "Klout",]
        dataType: 'script',
        success: function(data) {
            companyArray = data;
            console.log(companyArray); //displays the array of companies
            $('#companyInput1').attr('data-source', companyArray); //#companyInput1 is where the typehead should appear
            console.log($('#companyInput1').attr('data-source')); //returns undefined
        }
    });
}

UPDATES:

function dropDownList (evt) {
    console.log("dropdownfired");
    var companyArray = [];
    $.ajax({
        url : 'assets/data/companyarray.js', //this file contains ["Facbeook", "Twitter", "Klout",]
        dataType: 'script',
        success: function(data) {
            companyArray = data;
           console.log(companyArray); // shows the array of companies
            $('#companyInput1').data('data-source', companyArray);
            console.log($('#companyInput1').data('data-source')); // still returns undefined
        }
    });
}​

Answer №1

A best practice for storing data on HTML nodes is to only use strings as attributes. If you need to store an array, consider utilizing the .data()-method provided by jQuery.

success: function(data) {
        companyArray = data;
        console.log(companyArray); //displays array of companies
        $('#companyInput1').data('data-source', companyArray); //#companyInput1 holds typehead information
        console.log($('#companyInput1').data('data-source')); //expected output
    }

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

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Issue with Bootstrap modal not closing automatically after submitting an ajax form

I am facing an issue with a modal on my page that is used for submitting courses registered by students. Even after successful submission, the modal closes but leaves behind a faded background. I have attempted various solutions from StackOverflow without ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

text within the table is overlapping when being created dynamically in the <table> using javascript and jquery.quickflip.js

Hello everyone, I am currently working on dynamically generating a table using tabs created with jquery.quickflip.js. However, I have run into an issue where the text from one tab may overwrite values in another tab when switching between them. Below is ...

Guide on validating an email through a 6-digit code using Flutter, Node.js, and MongoDB

My goal is to create a registration process where users enter their email and password on a screen. After clicking "register", they should receive an email with a random 6-digit code for verification on the next page. I have everything set up, but I' ...

Is there a way to perform nested association counting in Sequelize?

Exploring ways to tally product reviews within nested associations using a specific query. const user = await User.findOne({ where: { id: req.query.user }, attributes: ["id", "name"], include: [ { model: Category, as: "interest ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

I am trying to map through an array fetched from Firebase, but despite the array not being empty, nothing is displaying on the

I retrieved an array of products from a firebase database using the traditional method: export const getUsersProducts = async uid => { const UsersProducts = [] await db.collection('products').where("userID", "==", uid).get().then(sn ...

Removing elements in AngularJS using ngRepeat

Many have questioned how to implement item removal within the ngRepeat directive. Through my research, I discovered that it involves using ngClick to trigger a removal function with the item's $index. However, I haven't been able to find an exam ...

Create your own AngularJS directive for displaying or hiding elements using ng-show/ng

Caution: Angular rookie in action. I'm attempting to craft a personalized widget that initially displays a "Reply" link, and upon clicking it, should hide the link and reveal a textarea. Here's my current progress, but unfortunately, it's n ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

The AJAX request for JSON data is functioning correctly in Firefox, but is experiencing compatibility issues with other web browsers

I recently completed a PHP page that generates a valid JSON document. The jQuery code used to fetch and display the data is quite straightforward: $.ajax({ url: "http://localhost:8888/rkm/json-jc", dataType: "json", success: function(data) { ...

Tips for incorporating a live URL using Fetch

I'm having some trouble with this code. Taking out the &type = {t} makes it work fine, but adding it causes the fetch to not return any array. let n = 12 let c = 20 let t = 'multiple' let d = 'hard' fetch(`https://opentdb.com/ ...

What kind of mischief can be wreaked by a malicious individual using JavaScript?

My mind has been consumed by thoughts about the safety of my projects, especially when it comes to password recovery. On the password recovery page, users must fill out a form with valid data and complete a recaptcha test for security. To enhance user ex ...

Check out the ViewUI Vue.js component that expands to reveal more content!

Is there a simple component to create the expand/collapse button with a blur effect like in all the demos? I see it used across different variations of the demos and am wondering if there is a specific component or demo showcasing how to achieve this effec ...

Session authentication mechanism designed to remain active only as long as the browser tab is open

Imagine you are developing a front-end application that utilizes a third-party API for authentication, with a successful authentication resulting in a JSON web token. What strategies would be most effective for storing this token and establishing a user s ...

Using v-for to show the values of an object in Vuetify

I am currently developing a function in vuejs that allows users to select tables from a database, with the columns' names automatically appearing in a v-list-item component. However, I am facing difficulty in displaying these column names effectively. ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

Arrange records in ascending order by phone number when multiple are returned on the same date

Currently, I am working on an Angular application that is designed to keep track of tuxedo rentals. The main feature of the app is a table that displays information from an array stored in the controller. The initial task I completed was listing the items ...