Choosing dynamic data with Select2

Currently, I am attempting to utilize select2 with jQuery 1.9.1 along with select2 3.3.0 for a relatively standard use case. My goal is to fill a select2 control with choices based on the status of another select2 control.

This is what I have:

<div>
  <select id="master" name="master">
    <option value=1>a</option>
    <option value=2>b</option>
  </select>
</div>
<div>
  <input type="hidden" id="detail" name="detail" data-placeholder="No options until master chosen">

<script src="jquery-1.9.1.js"></script>
<script src="select2-3.3.0/select2.js"></script>
<script>
var a = [];
var b = [];
for (var i = 0; i < 20; i++) {
  a.push({id: i, text: "a" + i});
  b.push({id: i, text: "b"+ i});
}

$(document).ready( function () {
  $("#master").select2().on('change', function() {
    console.log("master changed: " + $("#master").val())
    var right_one = a;
    if($("#master").val() == 2) right_one = b;
    $("#detail").removeClass('select2-offscreen').select2({data:right_one})
    console.log("right_one: " + right_one)
  })


})

Edit: This answer explains why the control was disappearing. However, I still have questions regarding this setup:

  1. Is there a way to prevent #master from having an initial selection?
  2. How can I modify the placeholder text in #detail to reflect the fact that a master option has been selected?

Answer ā„–1

When attempting to use the second select #detail, only clicking on options is effective as typing in a few characters will not produce the desired results.

Answer ā„–2

Perhaps a solution like the following:

<script>
var x = [];
var y = [];
for (var j = 0; j < 20; j++) {
  x.push({id: j, text: "x" + j});
  y.push({id: j, text: "y"+ j});
}

$(document).ready( function () {
    //set up default data, should work without one too
    $('#info').data('select2_values', []);
    $('#info').select2({
        allowClear: true,
        width: '150px',
        placeholder: 'No options until main chosen',
        query: function (query) {
            var data = {results: []};
            if (query.term == '')
            {
                data.results = $('#info').data('select2_values');
            }
            query.callback(data);
        },
        initSelection : function (element, callback) {
            var data = $(element).data('select2_values');
            if (typeof(data)!='object') data = [];
            callback(data);
        },
        data: $(this).data('select2_values')
    }).select2('disable');
    $('#main').select2({
        allowClear: true,
        width: '150px'
    }).on("change", function(e) {
        var selected_one = x;
        if ($('#main').select2('val') == 2) selected_one = y;
        $("#info").data('select2_values', selected_one);

        //Remove previous value if any
        $("#info").select2('val','');

        //If you want to select some vaoue you can use next line
        //$("#info").select2('data', selected_one[0]);

        //Enable 2nd box
        $("#info").select2('enable');
    });
});

</script>

Verified on chrome+win32

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 items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

Double-clicking with Ajax and JSF after the initial click

When I interact with a dataTable that has a column named DELETE (which is a link) and has a listener attached to it, I experience an issue. After clicking on the link for the first time (click 1), the row gets deleted as expected. However, subsequent click ...

Customize the asset path location in Webpack

I am currently working on a Vue application that utilizes Webpack for code minimization. Is there a method to dissect the chunks and adjust the base path from which webpack retrieves the assets? For example, by default webpack fetches assets from "/js" o ...

Trigger javascript function after clicking on two buttons

I am currently working on developing a web game inspired by Duolingo. In a specific scenario, I need a function to be triggered after two button clicks to progress further. However, I am facing challenges in finding solutions online or understanding it on ...

The two-dimensional array in JavaScript has not been defined

I've been trying to troubleshoot the error in my code with no success. I have a simple example of what I believe to be a two-dimensional array, but I keep getting an undefined error. var city = 'London', country = 'England'; ...

Struggling with synchronicity in javascript(node.js) and seeking assistance

I am faced with a challenge in my express.js app where I need to execute a script on the server, followed by running a couple of functions to derive some values. The process should be sequential, but I am running into issues as JavaScript seems to move on ...

Receiving successful ajax responses and populating text fields with the returned values

I have been attempting to populate the values from an AJAX success response into their corresponding fields, but I am encountering some difficulties. Despite receiving the desired data in the "alert(responseObject)" within the success section, I am unable ...

Adding a clear field icon to an input field: Step-by-step guide

When using AngularJS 1.3, a standard input field with type="date" comes with a convenient "Clear field" icon as shown here. Is there a method to incorporate this same "Clear field" icon into an input field with type="text"? ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Bootstrap 4 tabs function perfectly in pairs, but encounter issues when there are three of them

Having trouble with bootstrap4 tabs not working properly? They function well with 2 tabs using the code below: <div class="row"> <div class="col-12"> <ul class="nav nav-tabs" id="registration-picker-acc-select" role="tablist"> ...

Leveraging d3.js for Visualizations in an Angular2/Node/Express/MongoDB Application

Iā€™m working on integrating d3.js (https://www.npmjs.com/package/d3) into my project, and upon loading the page, I encounter a ZoneAwareError. After executing npm install d3 --save, all dependencies were successfully installed. Although I followed the gui ...

Create a specific part of a webpage that can be scrolled through

In a unique way, I have designed a page where the only way to navigate is by simply clicking. To achieve this, I have implemented the following custom CSS: body{ overflow:hidden; } However, I have encountered a problem where I am unable to scroll to ...

JavaScript code to prevent user from entering phone number

I operate a booking platform similar to AirBnB where users communicate with each other through messages on the site. My goal is to prevent users from sharing telephone numbers and email addresses within these messages. Currently, I am implementing a meth ...

Swapping out characters that are not numerical within a text input field

Is there a way to restrict the input in a text box to only numbers (1-5), a $(dollar) .(decimal) and '(singlequote) during a keyup event? I need a method that will replace any characters typed that are not part of this criteria with a *. Can you pleas ...

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

Using Vue.js to showcase Unicode, hexadecimal emojis, and octal literals in HTML

Received this response from the webserver: "\ud83d\ude48\ud83d\ude02\ud83d\ude30\ud83d\ude09\ud83d\udc4f\ud83c\udffd\ud83d\udc4c\ud83c\udffd\ud83d\udd1d\u2714&b ...

The 1.4.8 version of angular.js is throwing an error message labeled as $resource:badcfg. This error is showing up in the regular

After loading the page, Angular throws the following error: angular.js:12520 Error: [$resource:badcfg] http://errors.angularjs.org/1.4.8/$resource/badcfg?p0=query&p1=array&p2=object&p3=GET&p4=%2Fapi%2Fprospects%2Factive at Error (nativ ...

Modify the text on a button in ReactJS upon clicking

I am trying to change the text of a button when it is pressed. My goal is to achieve something similar to this example: https://codepen.io/gaearon/pen/xEmzGg?editors=0010, but I am having trouble getting my code to work (I'm new at this). class Obje ...