Setting a value in Select2 with a remote data source in js version 4.0.3

I encountered a situation in my application where we needed to display tags as separate values in a control, so we opted for Select2.

<select id="ddlGulfEmployee" multiple="multiple" style="display: none; 
 width: 
 100%;" class="form-control"></select>

</script>`$("#ddlGulfEmployee").select2({
    ajax: {
        url: '@System.Web.VirtualPathUtility.ToAbsolute("~/Home/GetMasterUser")',// '@Url.Action("GetMasterUser","Home") %>', //"../GetMasterUser",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            debugger;
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data) {
            debugger;
            var arr = []
            $.each(data, function (index, value) {
                //debugger;
                arr.push({
                    id: value.ID,
                    text: value.FirstName
                })
            })
            return {
                results: arr
            };
        },
        cache: true
    },
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: function (people) {
        debugger;
        //debugger;
        if (people.loading)
            return people.text;

        var markup = '<option value="' + people.id + '">' + people.text + '</option>';

        return markup;
    },
    templateSelection: function (people) {
        debugger;
        return people.value || people.text
    }
    //,
    //initSelection: function (element, callback) {
    //    debugger;
    //    callback($.map(element.val().split(','), function (id) {
    //        return { id: id, text: id };
    //    }));
    //}
});
$("document").ready(function () {//I WANT LIKE THIS OPTION 
    //1 russell 
    $('#ddlGulfEmployee').select2('val', ["test1", "test2"], true);

});

`

While saving and retrieving data from a remote source works well, I am facing an issue when trying to display the saved values back in the control during editing.

Your assistance on this matter would be greatly appreciated.

Thank you.

Answer №1

Give this code a try:

In this snippet, make sure you provide data in the form of key-value pairs.

$("document").ready(function () {
        $("#ddlGulfEmployee").select2({
               data: [
                {
                  id: '1',
                  text: 'option 1'
                },
                {
                  id: '2',
                  text: 'option 2'
                },
                {
                  id: '3',
                  text: 'option 3'
                }

              ]
        });
    });

You can also refer to this link for more information on select2 options.

I hope this explanation is clear.

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

Display additional information from a JSON file after choosing an ID with AngularJS Select

After saving a JSON file filled with information, I managed to successfully populate a select menu with the names of each element from the JSON data using this code snippet: <select ng-model="car.marca" ng-options="item.brakeId as item.name for item in ...

The Wicket AjaxSelfUpdatingTimerBehavior triggers a complete page refresh when accessed through two separate browser tabs

A label is checking for new notifications every 5 seconds and updating its text using AjaxSelfUpdatingTimeBehaviour. Everything works fine until I open another tab with the same page, then both tabs start refreshing the page instead of updating the label ...

jQuery and ajax method are failing to insert data into the database

I am having trouble inserting data into the database using jQuery and Ajax. Can someone please assist me in figuring out if I'm doing something wrong? Here is the code snippet: form.html <!DOCTYPE html> <html> <head> & ...

When using Cordova on Android, the getResponseHeader("Set-Cookie") function will only return the last cookie and not the entire list of cookies

When working with an Android platform in a Cordova project, the function getResponseHeader("Set-Cookie") only retrieves the last cookie from the response, unlike in the iOS platform where it retrieves all cookies. $.ajax({ type: "POST", cache:false, url: ...

Tips for arranging a column using a personalized display function in Handsontable

Handsontable version 0.34.2 (current version, unable to upgrade) I have a homepage displaying customer details using Handsontable. The first column is the ID column, which is a clickable HTML link. When clicked, it shows the customer's detailed infor ...

Obtain the ID of the chosen row within an MVC table

I'm a beginner in MVC and encountering an issue with obtaining the selected index of a table in an AJAX post request. Below is the structure of my classes: public class ContractModel { public long HotelId { get; set; } public long RateCodeI ...

Dynamic navigation experiencing erratic behavior when using display flex

I attempted to enhance my previous projects by converting them into flexbox. However, I ran into an issue where the ul element was displaying as a block. To fix this, I used JavaScript to change it to display flex. Here is the fiddle: // JavaScript co ...

What is the simplest method for moving cells between two tables using drag and drop?

Is there a way to select random cells from a table and move them to another table using drag and drop functionality? I'm looking for a library that can help achieve this with JavaScript and PHP. Additionally, I need to save the ID of the selected cel ...

Two clicks are needed for an AJAX call to be made

Can anyone help me figure out why my function is not displaying the content after one click? It seems to only work after two clicks. Is there a way to fix this so that the information loads and displays with just one click? function getFuncDoc(funcName, ...

Javascript menu toggle malfunctioning with sub-menus

I am in the process of creating a responsive menu for a complex website. The horizontal menu transitions into a vertical layout on smaller screens, with javascript used to toggle the sub-menu items open and closed when clicked. One issue I am facing is wit ...

Testing tools for ensuring the functionality and design of the mobile version of a

Is there a way to preview how my website will appear on mobile before it goes live? Most tools I've come across only work for hosted sites. ...

What is the most effective way to incorporate an Ajax partial page refresh in this specific code snippet?

I'm in the process of updating a specific section on my page. This particular section is enclosed in a division tag with a designated "class name". In order to keep things straightforward and avoid any confusion, I am seeking guidance on how to implem ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...

Positioning the slider based on the width

I've created a slider on my website: However, I noticed that when I slide to the right, there is some space between the image and the edge of the container. Despite setting everything's width to 1100px, I can't figure out where this extra s ...

"If the user presses the backspace key on the keyboard, jQuery will automatically navigate to the previous input

I'm currently working with a jQuery script: $(document).ready(function() { //Focus the first field on page load $(':input:enabled:visible:first').focus(); //Clear all fields on page load $(':input').each(function() ...

Browser freezing issue caused by jQuery each method while loading objects into the scheduler widget

I've been utilizing the DHTMLX scheduler for my project. The approach I'm taking involves making an AJAX GET request to retrieve data from the server and then loading the events using the addEvent() method. With a substantial amount of data to lo ...

What is the process for sending data to a node server using POST and receiving a responseText from it through GET?

Here is an example where I'm trying to send data from a JavaScript client to an Express Node server, validate the data against the database on the server, and respond once the verification process is complete. The data object in newHttpRequest.send(da ...

The correct method to access this LINK

Link to Image for Removal What is the correct method for calling the "Remove" link? How can I use jQuery to trigger the function when the "Remove" link is clicked inside a Bootstrap modal? Here is my HTML: <table> <tr> <td valign ...

Sending multiple form data using AJAX is a useful technique for submitting data

I have a dilemma - I’ve created a list where each row is a form with a submit button. Upon submitting the form, data is supposed to be sent via POST and update the div with the result. However, there seems to be an issue with how the data is being sent t ...

Stop the floating left div from wrapping onto a new line

My frustration is mounting as I have 4 divs set to float left, but the last one keeps wrapping onto a new line on smaller screens. I want them to scale with the screen size so they always stay on the same line, regardless of the screen size. I'm tryin ...