What is the best way to fill a "multiselect" element with information from a JSON object?

I'm struggling to populate the multiselect field with data from a JSON object. No matter which multiselect I use, the data shows in inspect mode but not on the frontend. It was supposed to look like this.

https://i.sstatic.net/FVz2H.png

but it comes out like this, with no options showing.

https://i.sstatic.net/aAOeU.png My HTML code:

<div>
   <span>Tags</span>
   <select id="choices-multiple-remove-button" placeholder="Select upto 5 tags"   name="tags" multiple></select>
</div>
            

My JavaScript code:

    success: function (data) {
    console.log(data);

    $.each(data, function (index, value) {
        var tagOption = ('<option value=' + value.Id + '>' + value.Name + '</option>');
        console.log(value.Name);
        $('#choices-multiple-remove-button').append(tagOption);

    });


    $(document).ready(function () {
        var multipleCancelButton = new Choices('#choices', {
            removeItemButton: true,
            maxItemCount: 5,
            searchResultLimit: 1,
            renderChoiceLimit: 2
        });
    });

My JSON data:

  {
    "Id": 1,
    "Name": "Tasty",
    "TimeStamp": null,
    "FOodOrTravel": 1
  },
  {
    "Id": 2,
    "Name": "Smells Bad",
    "TimeStamp": null,
    "FOodOrTravel": 1
  },
  {
    "Id": 3,
    "Name": "Spicy",
    "TimeStamp": null,
    "FOodOrTravel": 1
  },
  {
    "Id": 4,
    "Name": "Expensive",
    "TimeStamp": null,
    "FOodOrTravel": 1
  }

console.log(data) https://i.sstatic.net/qXrMM.png

Answer №1

$(document).ready(function () {
            $.ajax({
                
                url: 'https://codeforces.com/api/user.blogEntries?handle=Fefer_Ivan',
                method: 'GET',

                success: function (data) {
                    

                    $.each(data.result, function (index, value) {
                        var tagOption = ('<option value=' + value.id + '>' + value.title + '</option>');
                        
                        $('#choices-multiple-remove-button').append(tagOption);

                    });
                    var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
                removeItemButton: true,
                maxItemCount: 5,
                searchResultLimit: 5,
                renderChoiceLimit: 5
            });

                },
                error: function (jQXHR) {
                    if (jQXHR.status == "401") {
                        $('#errorModal').modal('show');
                    }
                    else {
                        $('#divErrorText').text(jqXHR.responseText);
                        $('#divError').show('fade');
                    }
                }
            });
            
        });
.mt-100 {
    margin-top: 100px
}

body {
    background: #00B4DB;
    background: -webkit-linear-gradient(to right, #0083B0, #00B4DB);
    background: linear-gradient(to right, #0083B0, #00B4DB);
    color: #514B64;
    min-height: 100vh
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006288/BBBootstrap/choices.min.css?version=7.0.0">
<script src="https://res.cloudinary.com/dxfq3iotg/raw/upload/v1569006273/BBBootstrap/choices.min.js?version=7.0.0"></script>
<div class="row d-flex justify-content-center mt-100">
    <div class="col-md-6"> <select id="choices-multiple-remove-button" placeholder="Select upto 5 tags" multiple>
    
        </select> </div>
</div>

Give this fully operational code snippet a whirl to assess its functionality according to your specific requirements. Enjoy discovering its capabilities! :)

[https://jsfiddle.net/mjg7r1q0/49/]

Your initial reference:

var multipleCancelButton = new Choices('#choices', {

The correct syntax should be:

var multipleCancelButton = new Choices('#choices-multiple-remove-button', {

Also, here's an alternative synchronous method if the script needs to wait for the asynchronous operation to finish:

https://jsfiddle.net/2bqp8zxo/2/

$(document).ready(function () {
            $.ajax({
                
                url: 'https://codeforces.com/api/user.blogEntries?handle=Fefer_Ivan',
                method: 'GET',
                async: false,
                success: function (data) {
                    

                    $.each(data.result, function (index, value) {
                      
                        var tagOption = ('<option value=' + value.id + '>' + value.title + '</option>');
                        
                        $('#choices-multiple-remove-button').append(tagOption);

                    });
                    

                },
                error: function (jQXHR) {
                    if (jQXHR.status == "401") {
                        $('#errorModal').modal('show');
                    }
                    else {
                        $('#divErrorText').text(jqXHR.responseText);
                        $('#divError').show('fade');
                    }
                }
            });
            var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
                removeItemButton: true,
                maxItemCount: 5,
                searchResultLimit: 5,
                renderChoiceLimit: 5
            });
        });
.mt-100 {
    margin-top: 100px
}

body {
    background: #00B4DB;
    background: -webkit-linear-gradient(to right, #0083B0, #00B4DB);
    background: linear-gradient(to right, #0083B0, #00B4DB);
    color: #514B64;
    min-height: 100vh
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"...

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

Revolutionary Knockout-Kendo MultiSelect Feature: Pressing Enter Erases Previously Selected Options

When using the Knockout-Kendo MultiSelect control, I have encountered an issue. If I select a value from the list, then enter a second value and press enter, the previously entered values are removed. VIEW <select data-bind="kendoMultiSelect: { da ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

AngularJS Error: $interpolate:interr - Encounter with Interpolation Error

Having some trouble embedding a YouTube video into my website using AngularJS. Keep receiving this pesky error: Error: $interpolate:interr Interpolation Error Any idea why this error is popping up and how I can resolve it? Just trying to add the video... ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Issue with Semantic-UI Special PopUp not displaying on screen

I'm currently working on creating a unique pop-up feature using custom HTML, with the intention of adding content to it later on. My console is displaying the following message: Popup: No visible position could be found for the popup. $(document) ...

The LinkedIn API encountered an error when attempting to retrieve historical follower data, resulting in a HTTP

I've scoured the depths of the internet in search of a solution to my problem, but none seem to fit what I need. My goal is to retrieve historical follower data from LinkedIn's API using this call: ${companyId}/historical-follow-statistics?time- ...

Utilizing jQuery's extend method for object inheritance in a function

I've been experimenting with using jquery extend to simulate inheritance, but it seems that it only works with objects based on my testing. My goal is to achieve the following: var baseDefinition = function() { var self = this; self.calc1 = ...

Changing a global variable via an AJAX call

I seem to be facing a common issue that many others have encountered. Despite my understanding that global variables can be modified inside functions in Javascript, I am struggling with this concept in practice. var lastMessage = 0; function loadChat() { ...

Retrieve a result following an AJAX post request to utilize the obtained value in subsequent code functionalities

Below is the code snippet where an "if" statement is used to check if a query has been executed correctly. If it has, a part of the script is stored in a variable called $output. This variable is then immediately read by the notification script included in ...

Can I retrieve the element of any DOM element I'm currently hovering over using JavaScript?

Suppose I have this HTML snippet: <body> <div id="1"> <span class="title">I'm a title!</span> </div> <div id="2">I'm the first element!</div> <div ...

Is there a way for me to determine the dimensions of the webcam display?

How do I determine the width and height of the camera in order to utilize it on a canvas while preserving proportions? I am attempting to ascertain the dimensions of the camera so that I can use them on a canvas. On this canvas, I plan to display live vid ...

JavaScript Array join() method returns an empty string

As a beginner in the world of javascript, I am just starting to dip my toes into it. In the past, I have used join() without any issues, but now I am facing a problem where this join is returning an empty string. Upon inspecting myArray, the data seems t ...

What is the process for verifying the ongoing sessions within a particular set of classes?

I have a list of 10 items with varying active classes based on user interactions. I need to determine the number of sets of 3 consecutive active classes within the list. In the given example, there are 2 sets of 3 consecutive active classes: 4,5,6 and 8,9, ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

There appears to be no data available from the Apollo Query

I'm facing an issue with the returned data from Apollo Query, which is showing as undefined. In my code snippet in Next.js, I have a component called Image with the src value set to launch.ships[0].image. However, when running the code, I encounter a ...

The loop feature in Swiper.js seems to be malfunctioning and not functioning as

I'm currently in the process of setting up a carousel using swiper.js and here is my setup: { slidesPerView: 1, slidesPerColumn: 1, initialSlide: this.initialSlide, loop: true } As expected, I'm encountering an issue where dupl ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...