Troubleshooting issue with refreshing selectpicker in Bootstrap-select and Vue.js

Incorporating the bootstrap-select plugin (found at ) into a ruby on rails app with Vue.js as the javascript framework has been my latest project.

The goal is to have two select options where one selects a category and the other displays all available teachers for that selected category. I am utilizing axios and vue to make a request to my API and populate the second select field. While this works perfectly fine with a simple select field, I want to use bootstrap-select for a better user interface experience. The issue arises when trying to refresh the options using the "selectpicker('refresh')" function of the plugin. Although it works when manually executed in the browser console, calling it on my vue instance triggers a 'selectpicker is not a function' error in the console.

Here is a snippet of my code:

Javascript:

Vue.use(VueAxios, axios)
    document.addEventListener('DOMContentLoaded', () => {
      if(document.getElementById('enrollment_form')) {
      var app = new Vue({
        el: '#enrollment_form',
        data: {
          CategoryValue: null,
          TeacherValue: null,
          teachers: null,
        },
        methods: {
          fetchTeachers() {
            this.axios.get('/api/teachers/' + this.licenceTypeValue).then(response => (this.teachers = response.data))
              $('.selectpicker').selectpicker('refresh');
          }
        }, 
      })
    }})

View:

       <div class="row">
          <div class="col-lg-5">
            <div class="form-group">
              <%= f.label :category %>*<br />
              <%= f.collection_select(
                  :category,
                  Category.all,
                  :id,
                  :catgegory_name,
                  {include_blank: true},
                  {
                    class: 'form-control selectpicker',
                    "v-model" => "CategoryValue",
                    "v-on:change" => "fetchTeachers"

                  }
              )%>
            </div>
          </div>  
        </div>

        <div class="row">
          <div class="col-lg-5">
            <div class="form-group">
              <label for="teacher_id">Teacher</label>
              <div>
                <select id="teachers-list" class='form-control selectpicker' v-model="TeacherValue" data-fieldname = "TeacherValue">
                  <option label="" ></option>
                  <option v-for="teacher in teachers" :value="teacher.id"> {{teacher.name}}  </option>
                </select>
              </div>
            </div>
          </div>  
        </div>

        <div>
          <%= f.hidden_field :teacher_id, {"v-model" => "TeacherValue"} %>
        </div>

Lastly, my application.js file includes:

//= require rails-ujs
//= require activestorage
//= require jquery
//= require jquery_ujs
//= require popper
//= require bootstrap
//= require bootstrap-select

If anyone could provide assistance, I would greatly appreciate it as I am currently stuck and unable to find a solution.

Answer №1

If you encounter a similar issue, consider making the following changes:

let vm = new Vue({
    el: '#enrollment_form',
    data: {
        CategoryValue: null,
        TeacherValue: null,
        teachers: null,
    },
    methods: {
        retrieveTeachers() {
            // Store the Vue object in a variable to retain context for subsequent use within the 'then' block 
            // as 'this' will be redefined.
            let vueInstance = this;

            this.axios
                .get('/api/teachers/' + this.licenceTypeValue)
                .then(response => {
                    vueInstance.teachers = response.data;
                    // Utilize Vue's $nextTick function to guarantee that bootstrap-select is refreshed after the update has completed.
                    vueInstance.$nextTick(function(){ $('#teachers-list').selectpicker('refresh'); });
                });
        }
    }, 
})

I faced a similar challenge while working on a project and documented my findings in an informative article, which includes both faulty and functional demos. Although my examples focus on altering options through JavaScript sans AJAX, the fundamental principle remains unchanged.

In the provided code snippet, the 'refresh' method of bootstrap-select is triggered using Vue's $nextTick function, ensuring its execution post-update completion by the Vue object. (refer to Vue documentation on $nextTick)

Note: A broader approach can also incorporate a generic update in the Vue 'update' event handler:

updated: function(){
  this.$nextTick(function(){ $('.selectpicker').selectpicker('refresh'); });
}

It is important to note that this tactic would universally refresh all selectpickers sharing the 'selectpicker' class. This repeated update may affect performance and result in inefficiency, especially if it occurs with unrelated vue data updates.

Optimally, selectively refreshing only the affected <select> at the precise moment necessitating the refresh (i.e., upon the return of the AJAX call and successful update of the 'teachers' property) is advisable.

Answer №2

Running this code within a timeout function will trigger a refresh.

 setTimeout(function () {
            $(".selectpicker").selectpicker("refresh");
        }, 1000);

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

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Evolution of Vue lifecycle in Vue2

I am currently in the process of migrating from Vue2 to Vue3. To ensure a smooth transition, I want to make changes that Vue2 can handle before moving on to Vue3. Here are the updates in Vue3 lifecycle: My plan is to implement these changes and add setup( ...

The transformation in the resulting array is evident when a nested array is altered after being concatenated using Array.concat

MDN explains concat as follows: The concat() function is utilized to combine two or more arrays without altering the original arrays. Instead, it produces a new array. Let's examine the code snippet below: Example 1 const array1 = [['a& ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Issue with modal component triggering unexpected page reload

I'm encountering a strange issue with my modal in Vue.js. It only appears on a specific page named 'Item', but when I click on a different view, the page reloads unexpectedly. This problem seems to occur only with the route containing the mo ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

What could be causing this code to continuously loop without end?

I've been scratching my head trying to understand why this code isn't working. var refP = []; var calculateDistance = function (p1, p2) { return dist(p1.x, p1.y, p2.x, p2.y); } while (refP.length < 24) { var point = { x: -1, ...

When the user clicks the back button in AngularJS

After searching extensively, I have yet to find a straightforward solution to my issue. The problem lies in a search/filter field that filters the page based on user input. While this filter works efficiently, it clears whenever a navigation item is clicke ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Exploring time differences in Javascript

I am trying to save a JSON AJAX response from the server in the browser's localStorage for a duration of one minute, along with a timestamp generated using new Date().getMinutes(). Upon triggering $(document).ready, I aim to check the stored timestam ...

Creating specialized validation for numeric fields in Angular2

Attempting to implement custom validation in Angular 2 has been a challenge for me. I have followed the necessary steps based on my understanding, but still struggling to get it working. import { FORM_DIRECTIVES, AbstractControl, ControlGroup ,FormBuilder ...

Inquiries regarding real-time alerts and notifications

Just curious, I am wondering about the creation of those notifications/alerts (for example on platforms like twitchalerts, commonly used by livestreamers). Are they typically coded in JavaScript/AJAX or another language? Is there a specific framework for ...

Is there a way to transform the searchParams function into an object? Changing from URLSearchParams { 'title' => '1' } to { title : 1 }

Is there a way to convert the searchParams function into an object, transforming from URLSearchParams { 'title' => '1' } to { title : 1 }? I need this conversion to be applied for all values in the URLSearchParams, not just one. Curren ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...