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

eliminate the script and HTML comment from a designated division

Here is the default code that I need to modify using JavaScript to remove scripts, comments, and some text specifically from this div: I came across this script that removes all scripts, but I only want to remove specific ones from this div: $('scri ...

fetch and parse JSON data using jQuery

I am currently developing a basic chatbox using Zend Framework and JQuery. I am using $('#outputArea') to load the content, which is essentially a div with $.load(). However, the response I get is a JSON object with multiple messages that I need ...

Browser displaying a CSS error: "Invalid property name" while applying pseudo-element :after

I encountered an issue in Chrome and Explorer while attempting to set a CSS property for a pseudo element :after. (I'm trying to create a styled burger nav icon) The error message I received was: 'Unknown property name' This happened wh ...

Node and Socket.IO - Personalized messaging (one-on-one)

I'm in the process of developing a one-on-one chat feature using Socket.IO and Express to enable private messaging between users. The main issue at hand is: I am looking for a way to send a private message to a specific socket.id while ensuring that ...

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...

Stopping package.json from updating dependencies

I am curious if there is a method to prevent the package.json file from automatically updating to the latest versions of dependencies it includes. The main reason for wanting to avoid these updates is that I rely on running specific scripts with certain l ...

Is it true that Firefox fails to display javascript errors on AJAX 'threads'?

Currently, I have a function called test_fn that is being called in two ways: (a) Through an onclick event of a button; or (b) from the success callback within a jQuery AJAX request, as shown here: $.ajax({ type: 'POST', ... succes ...

Identify when the user clicks on the URL bar or types in the browser's address bar using Jquery or JavaScript

In my current project, I'm faced with the challenge of interacting with the browser's URL bar. Specifically, I need to detect events using jQuery/JS when a user clicks on the address bar, types in it, or switches tabs. Is there a way to achieve t ...

Switching from Vanilla JS to Vue.js, dealing with querySelector problems

Seeking assistance with transforming the following CodePen example to a Vue.js component: https://codepen.io/kjbrum/pen/qooQJJ While attempting to incorporate this.$nextTick for handling DOM manipulation, I'm encountering challenges in making it func ...

In JavaScript, the Else statement fails to run

Hi there, I'm currently working on creating a function to check the validity of a string input. This is what I have so far: function validatePassword(){ passW = prompt ("Enter Password:"); if (passW == 'Pass123'){ document.write ('Y ...

Regular expression designed to validate a 19 digit MasterCard number

I need assistance with adjusting the regex pattern for Mastercard to support both 19 digit and 16 digit cards. Can someone please provide guidance on how to modify it? masterCardPattern: /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0- ...

jQuery failing to implement Lazy Load feature when retrieving images

Hello everyone, I have a query regarding lazy loading images on my website. I am successfully fetching the first 10 data from the server side, but when I load the next 10 data using jQuery AJAX, the lazy load function does not work on the new data. $(wind ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Sending the most recent information in the DataTable's ajax post request

Take a look at the code snippet below for refreshing jquery DataTable: In cshtml: <table id="companies" class="table table-bordered table-responsive table-hover"> <thead> <tr> <th></th> &l ...

The loss of Webgl context that remains unrecovered

I am facing an issue with the loss and restoration of webgl context. My application is quite complex, containing a lot of data, graphs, lists, and maps. Within the map section, I utilize webGL to ensure optimal performance. My code effectively manages th ...

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

Calculating the time difference in days, hours, minutes, and seconds between two UNIX timestamps

I have a special occasion coming up, and the date and time for this event are stored in a Unix timestamp format. Instead of relying on a plugin like modern.js, I am trying to figure out the time difference between today's date and the event date usin ...

Using Javascript closures for managing asynchronous Ajax requests within for loops

Let's consider the arrays provided below. var clients = ['a','b']; var reports = ['x','y','z']; var finalData = []; Now, I aim to iterate through them in a specific manner as shown. for(var i=0;i< ...

Access parent component's properties by clicking on child component

I'm uncertain if my current approach is the most effective solution to my issue, so I am open to alternative methods. My goal is to access the properties of the parent component when clicking on a child component (Image). Below is the code I have imp ...

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...