Having trouble sending AJAX select options with Choices.js

I'm currently utilizing Choices.js (https://github.com/jshjohnson/Choices) along with Ajax to dynamically populate data into my select field from a database. However, I've encountered an issue when using the following code:

const choices = new Choices('select',
  {
    loadingText: 'Loading...',
    searchEnabled: false,
    itemSelectText: '',
    removeItemButton: true,
  });

The dynamic select field ceases to work and the data doesn't get populated from the ajax script. The information is supposed to be fetched dynamically from the DB for the first select - course field. When I remove the above choices parameters, everything functions properly. But when I include it, the functionality breaks and the remote ajax data fails to populate.

Any suggestions on how to enable ajax data from the DB to show up in Choices.js?

I noticed there's an option to add choices using setchoices: https://github.com/jshjohnson/Choices#setchoiceschoices-value-label-replacechoices

I am unsure of how to implement those in my code. Any assistance would be greatly appreciated!

Here's the HTML snippet:

<div class="input-field">
            <div class="input-select">
            <select name="course_id" id="course_id" class="form-control input-lg dynamic" data-dependent="branch_id">
                <option value="">Select Course</option>
                @foreach($papers as $paper)
                <option value="{{ $paper->course_id}}">{{ $paper->course_name }}</option>
                @endforeach
            </select>

            </div>
          </div>
      <br>
      <div class="input-field">
            <div class="input-select">
            <select name="branch_id" id="branch_id" class="form-control input-lg dynamic" data-dependent="sem_id">
              <option value="">Select Branch</option>

            </select>

            </div>
          </div>
          <br>
    <div class="input-field">
            <div class="input-select">
            <select name="sem_id" id="sem_id" class="form-control input-lg">
              <option value="">Select Semester</option>
            </select>

            </div>
          </div> 

And here's the Ajax portion:

<script type="text/javascript">
$(document).ready(function(){


$('.dynamic').change(function(){
 if($(this).val() != '')
 {
  var select = $(this).attr("id");
  var value = $(this).val();
  var dependent = $(this).data('dependent');
  var _token = $('input[name="_token"]').val();
  $.ajax({
   url:"{{ route('dynamicdependent.fetch') }}",
   method:"POST",
   data:{select:select, value:value, _token:_token, dependent:dependent},
   success:function(result)
   {
    $('#'+dependent).html(result);
   }

  })
 }
});

$('#course').change(function(){
 $('#branch').val('');
 $('#sem').val('');
});

$('#branch').change(function(){
 $('#sem').val('');
});


});

</script>

Answer №1

Utilize settimeout to improve performance

setTimeout(function () {
    const choices = new Choices('[data-trigger]',
        {
            searchEnabled: false,
            itemSelectText: '',
        });
}, 500);
function loadCategoryProduct() {
    $.ajax(
        {
            type: "POST",
            url: "/Product/GetProductCategory",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "true",
            cache: "false",
            success: function (data) {
                var s = '<option placeholder="" value="0">Danh mục</option>';
                for (var i = 0; i < data.length; i++) {
                    s += '<option value="' + data[i].ProductCategoriesID + '">' + data[i].ProductCategoriesName + '</option>';
                }
                $("#ddlProductCategory").html(s);
                if (idCategoryProduct == "") {
                    $('#ddlProductCategory').val(0);
                }
                else {
                    $('#ddlProductCategory').val(idcountry);
                }
                setTimeout(function () {
                    const choices = new Choices('[data-trigger]',
                        {
                            searchEnabled: false,
                            itemSelectText: '',
                        });
                }, 500);
                
            },
            Error: function (x, e) {
                //alert("Some error");
            }
        });
}

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

Easily move elements using a jQuery click animation

Having trouble animating a div's top position by -130px to move it off screen? Can't figure out why it's not working? I'm fairly new to jQuery/Javascript. I have a button/hyperlink with the ID #NavShrink. When clicked, I want the div # ...

Using jQuery to dynamically select all rows (`tr`) that contain table data cells (`td`) matching

Although my title may seem confusing, it's the best I could come up with. I'm looking to identify all tr elements that contain td elements matching specific filter criteria. Here is an example: <tr class="row" id="1"> <td class="ph ...

Selecting a date in Jade's date picker

I'm currently facing an issue with getting a datepicker to function properly using Jade in a node.js and express framework. Within index.jade, I am loading the necessary javascript files like this: link(type='text/css', href='css/ui-l ...

What is the best way to retrieve a specific property from a JSON object in the data received from an

Currently, I am working on an AJAX call that targets this PHP file: <?php $response = array('error' => "Please provide a valid name"); echo json_encode($response) ?> Within my JavaScript file, the following code is implemented ...

AngularJS: Transitioning from Expressions to Javascript (Coffeescript)

Looking to convert an expression into JavaScript in order to maintain an object's value in $scope: <dl class = "mortgage-information"> <dt><abbr title = "Loan-to-value Ratio">LTV</abbr></dt> <dd>{{(total_fi ...

Information not displayed in the chart

Every time I submit the form, an empty table is displayed instead of showing the data. I'm not sure why this is happening, can someone please assist? This is my form: <form action="{{ URL::to('/orderTracking') }}" id="otpF ...

Unable to decipher the mysterious map of nothingness

I am currently working on a GET method in Node.js. My goal is to fetch data using the GET request and then use the MAP function to gather all the names into an array. However, I encountered the following error: /root/server.js:21 ...

I am interested in incorporating a captcha system using ajax

Recently, I implemented email and captcha validation in a form. Now, I am looking to make some modifications. Specifically, I want the form to not reload the page if the captcha is incorrect or left empty. This means that all fields that have already bee ...

Resolve CORS error when uploading images with AJAX and Node.js using FormData

I am incorporating vanilla javascript (AJAX) to submit a form and utilizing Formdata(). The submission of the form is intercepted by nodejs and linked to a database. However, there is an issue that arises when I try to connect with nodejs after adding a f ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

Angular Controller encounters issue with event handler functionality ceasing

One of my Angular controllers has the following line. The event handler works when the initial page loads, but it stops working when navigating to a different item with the same controller and template. document.getElementById('item-details-v ...

Combining Multiple Ajax Calls into a Single Ajax Request using jQuery

I have several ajax calls in my Javascript file and I am looking to consolidate them into a single ajax call. Below is a snippet of my JS code. var vpnPin = $.ajax({ dataType: "json", url: "url", async: true, success: function(result) {} ...

What is the method to modify the text of an element without altering its existing properties?

https://i.stack.imgur.com/cBu6P.png $.ajax({ type: "GET", url: "my url" + x, datatype: "html", success: function(data){ //alert(x); //var Content = data; var sendId ; var data = $.parseJSON(data); ...

Using jQuery to assign a specific value to all select boxes

I am facing a challenge where I need to change the values of all select boxes on my page to a specific number. Here is the HTML structure: <select> <option value="-1" <option value="55">ENABLE</option> <option value= ...

Guide for implementing smooth fade in and out effect for toggling text with button click

I have this code snippet that toggles text on button click: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function toggleText(){ ...

Can Jquery mobile detect drag gestures?

Is there an event in Jquery Mobile that allows you to hide/show a div by dragging it, similar to the effect seen on phones? I have searched on different platforms and found that using Jquery UI is the closest solution. Is it possible to achieve this only ...

Having trouble converting the file to binary format in order to send it to the wit.ai api through node.js

I am having trouble converting an Audio file to Binary format for sending it to the Wit.AI API. The node.js platform is being used for this purpose. On the front-end, user voice is recorded using the Mic-recorder Module. Any guidance or suggestions would b ...

Sending a form cancellation submission within a nested function call

I need help preventing my form from submitting in case the confirmation message is cancelled. How can I achieve this within the each() loop? $('#myForm').submit(function() { var inputs = $(this).find('input:checked'); inputs.ea ...

What is the best way to determine the index of the area that was clicked on in chartjs?

I am currently working with a chart that may not have elements at specific indices, but I am interested in determining the index of the area clicked. https://i.sstatic.net/rEMbG.jpg When hovering over an area without an element, the assigned tooltip is d ...

Dynamic and static slugs in Next.js routing: how to navigate efficiently

I am facing a scenario where the URL contains a dynamic slug at its base to fetch data. However, I now require a static slug after the dynamic one to indicate a different page while still being able to access the base dynamic slug for information. For Ins ...