Modify select option in Bootstrap Vue based on user input

I am facing a challenge in populating a Bootstrap-Vue form select with objects obtained via JSON. The JSON data comprises teacher information from various fields:

[
  {
    "id": 1,
    "name": "John",
    "surname": "Doe",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e44414640004a414b6e49434f4742004d4143">[email protected]</a>"
  }
]

My goal is to display the full name (concatenating name and surname) of each teacher in the select list.

Previously, I successfully achieved this by using a computed property to process the list and display the names. However, now I want to filter the list of courses based on the selected teacher.

To accomplish this, I require access to the teacher's email address which I have currently omitted while processing the teacher names for display.

As a result, I am unable to update the course list dynamically according to the selected teacher.

Below is the template code snippet:

<b-form-group
  id="input-group-3"
  label="Docente:"
  label-for="input-3"
>
  <b-form-select
    v-model="teacher"
    :options="teachers"
    value-field="item"
    text-field="fullName"
    required
    @change="filterCourse"
  ></b-form-select>
  <div class="mt-3">
    Selected: <strong>{{ teacher }}</strong>
  </div>
</b-form-group>

This is the script code snippet:

import { mapGetters, mapActions } from "vuex";
export default {
  data() {
    return {
      teacher: "",
      course: "",
    };
  },

  created: function() {
    this.GetActiveTeachers();
    this.GetActiveCourses();
  },

  computed: {
    ...mapGetters({
      ActiveTeacherList: "StateActiveTeachers",
      ActiveCourseList: "StateActiveCourses",
      FilteredTeacherList: "StateTeacherByCourse",
      FilteredCourseList: "StateCourseByTeacher",
    }),

    teachers: function() {
      let list = [];
      this.ActiveTeacherList.forEach((element) => {
        let teacher = element.name + " " + element.surname;
        list.push(teacher);
      });
      return list;
    },
  },

  methods: {
    ...mapActions([
      "GetActiveTeachers",
      "GetActiveCourses",
      "GetCourseByTeacher",
      "GetTeacherByCourse",
      "AssignTeaching",
    ]),

    async filterCourse() {
      const Teacher = {
        teacherEmail: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="076d686f692963686247606a666e6b2964686a">[email protected]</a>", // For testing purpose
      };
      try {
        await this.GetCourseByTeacher(Teacher);
      } catch {
        console.log("ERROR");
      }
    },

    async filterTeacher() {
      const Course = {
        title: "Programming", // For testing purpose
      };
      try {
        await this.GetTeacherByCourse(Course);
      } catch {
        console.log("ERROR");
      }
    },
  },
};

Answer №1

If you're currently using the most basic notation for form selects in Bootstrap Vue, which is an array of strings, I recommend switching to their object notation instead.

This will allow you to define the text (what appears in the list) separately from the value (what gets sent to the select's v-model).

By making this change, you can access all the necessary data from the teacher object while customizing what information is displayed.

To implement this, replace the forEach() method in your computed property teachers with the map() function:

teachers() {
  return this.ActiveTeacherList.map((teacher) => ({
    text: teacher.name + " " + teacher.surname,
    value: teacher
  }));
},

Subsequently, update your filterCourse() handler to reflect these changes, for example:

async filterCourse() {
  const Teacher = {
    teacherEmail: this.teacher.email,
  };
  try {
    await this.GetCourseByTeacher(Teacher);
  } catch {
    console.log("ERROR");
  }
},

It's worth noting that you have the flexibility to shape the value however you like if you don't require the entire object. For instance, if you prefer to display the full name and email:

value: { 
  fullName: teacher.name + " " + teacher.surname,
  email: teacher.email
}

Answer №2

Consider these two options for implementation.

The first approach involves manually generating the <option> elements within the select tag by utilizing a v-for loop on your list of teachers. Bind the teacher's email to the value attribute, and display their name and surname within the option tags.

By implementing this method, the v-model of your <b-select> will return the selected teacher's email, which can then be utilized in your filter function.

new Vue({
  el: '#app',
  data() {
    return {
      selectedTeacher: null,
      activeTeachers: [{
          "id": 1,
          "name": "Dickerson",
          "surname": "Macdonald",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77131e141c1205041819591a1614131819161b1337120f161a071b125914181a">[email protected]</a>"
        },
        {
          "id": 2,
          "name": "Larsen",
          "surname": "Shaw",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7cbc6d5d4c2c989d4cfc6d0e7c2dfc6cad7cbc289c4c8ca">[email protected]</a>"
        },
        {
          "id": 3,
          "name": "Geneva",
          "surname": "Wilson",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d2d0dbd0c3d49bc2dcd9c6dadbf5d0cdd4d8c5d9d09bd6dad8">[email protected]</a>"
        }
      ]
    }
  }
})
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e7c71...[email protected]</a>" rel="stylesheet" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-...[email protected]</a>/dist/bootstrap-vue.js"></script>


<div id="app">
  <b-select v-model="selectedTeacher">
    <option v-for="teacher in activeTeachers" :value="teacher.email">
      {{ teacher.name }} {{ teacher.surname }}
    </option>
  </b-select>

  {{ selectedTeacher }}
</div>


Alternatively, you can modify your computed property to return an array of objects instead of simple strings.

When using an array of objects in the options prop of <b-select>, it expects the properties value and text.

In this scenario, bind the teacher's email to the value property and their name and surname to the text property.

Similar to the previous method, the v-model of your <b-select> will return the chosen teacher's email for further utilization in your filter logic.

For more details, refer to:

new Vue({
  el: '#app',
  data() {
    return {
      selectedTeacher: null,
      activeTeachers: [{
          "id": 1,
          "name": "Dickerson",
          "surname": "Macdonald",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690d000a020c1b1a06074704080a0d060708050d290c11080419050c470a0604">[email protected]</a>"
        },
        {
          "id": 2,
          "name": "Larsen",
          "surname": "Shaw",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86eae7f4f5e3e8a8f5eee7f1c6e3fee7ebf6eae3a8e5e9eb">[email protected]</a>"
        },
        {
          "id": 3,
          "name": "Geneva",
          "surname": "Wilson",
          "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1176747f7467703f66787d627e7f517469707c617d743f727e7c">[email protected]</a>"
        }
      ]
    }
  },
  computed: {
    teacherOptions() {
      return this.activeTeachers.map(teacher => ({
        value: teacher.email,
        text: `${teacher.name} ${teacher.surname}`
      }));
    }
  }
})
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24464b4b50575056455464100a110a17">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88fefdedc8baa6bea6b9ba">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a3...[email protected]</a>/dist/bootstrap-vue.js"></script>


<div id="app">
  <b-select v-model="selectedTeacher" :options="teacherOptions"></b-select>

  {{ selectedTeacher }}
</div>

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

Does anyone know how to begin implementing Opentelemetry browser instrumentation for a vue.js application?

import { WebTracerProvider, BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-web'; import { ZoneContextManager } from '@opentelemetry/context-zone'; import { Resource } from '@opentelem ...

I'm having trouble with my script only fetching the first row of my PHP table. Can someone please take a look at my code

Below is my JavaScript snippet: $('input#name-submit').on('click', function() { var name = $('input#name-submit').val(); if($.trim(name) != ''){ $.post('getmodalreasonUT.php', {name: name}, ...

Limit the v-text-field input to only accept a single digit

I am currently working on creating an SMS verification code component using a series of v-text-field components. My goal is to limit the input to just a single digit. <v-text-field v-for="(num, key) of code" :key=" ...

Storing information in an array based on a specific flag

Currently, I am developing an Angular application where I am dealing with a specific array that contains a flag named "checked". Based on the value of this flag, I need to perform certain manipulations. Here is a snippet of my sample data: const data = [{ ...

What is the process for searching a specific column in a Vuetify v-data-table that is not included in the headers?

Header for Product Data: headers: [ { text: "Product Name", value: "name" }, { text: "Quantity", value: "quantity" }, { text: "Price", value: "price" }, { text: "Orders", value: &quo ...

utilizing the entire string rather than just a portion

I was attempting to create a JavaScript jQuery program that vocalizes numbers based on some previously saved data. However, I encountered an issue where only the last number in the sequence was being played (the final character in the string). Below is t ...

The State of NgRX Entity is encountering undefined IDs

I decided to experiment with @ngrx/entity in a simple "Todo" project, where I had only one AppModule, one reducer, and a single component. However, as I delved into it, I encountered some challenges. The actions I defined were quite basic, focusing on CRU ...

Bootstrap 4 - How to Properly Align Text within Lists

Recently, I started experimenting with Bootstrap 4 and encountered an issue with centering text in a list-group. In Bootstrap 3, the following CSS rule worked like a charm: .list-con { text-align:center; } However, in Bootstrap 4, the text-align prope ...

Transferring information between two tables in a MongoDb database

My current database in mongo is named "sell" and it contains two tables: "Car" and "Order". In the "Car" table, there is an attribute called "price". When I run the following command in the mongo shell: db.Order.aggregate([ { $lookup: { from: ...

steps for making personalized video embed dimensions in bootstrap

Update: I have successfully integrated a non-standard bootstrap video size with proportions of 4x5. However, unlike standard bootstrap embeds, it doesn't seem to adhere to a maximum height no matter where I place it - on the iframe or div elements ar ...

Switching from React Router version 3 to 4.1.1, what is the best way to organize my routes separately from my app.jsx file?

After successfully running a site with React Router 3.0.5, I decided to update to React Router 4.1.1 which resulted in some errors. My main goal is to have the root route as "/" leading to the app component, while other routes are directed elsewhere. An e ...

Is there a way to load and play different sounds on multiple audio players based on the length of an array?

I am attempting to load various sounds (.mp3 audio) on separate audio players that are displayed on a single HTML page. The number of players displayed on the screen is determined by the length of the array. In this specific example, I have 3 elements in t ...

Filtering nested objects in JavaScript based on a specific property value

I have a list of objects nested in JavaScript and I need to filter them based on a specific search string and property value. My goal is to extract only the categories with children that are not hidden and contain at least one profile with a name matching ...

The tooltips in the WordPress-Gulp-Starter-Kit running on Bootstrap 5 do not seem to be functioning properly

I'm having trouble with tooltips not working properly. The codebase I'm using is from this repository https://github.com/oguilleux/webpack-gulp-wordpress-starter-theme If you need more details, feel free to reach out. Here is my main.js file: ...

Trigger a JavaScript function on a body click, specifically targeting certain elements to be excluded

I have a dropdown menu within a div element. I've created a javascript function called HideDropdown() that hides the menu when any main link on the page is clicked, except for links within the dropdown menu itself: <script> function HideDropdow ...

Customize Vue or Nuxt by including a highly detailed tag in the <head> section

Trying to generate static page templates using Vue/Nuxt but struggling to find a way to insert a very specific tag into the head section of each generated page. It's not a meta, script, style, or link tag, and it appears that the options in nuxt.confi ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Is it possible to apply data filtering in a table by clicking on a specific segment of a pie chart within a Laravel Vue application?

After successfully implementing the click event for the chart to filter the data in the table, I am encountering an issue where not all the data in the table is returned when clicking outside the chart area. How can I ensure that all the data is returned w ...

What is the best way to convert a JSON string from a specific array into an array object?

JSON object: { "data": { "myStatus": "[1 2 21 0 50 0 0 0],[2 1 3 1 50 0 0 0]" }, "success": true } Upon converting to the JSON object, it appears that the myStatus is being treated as a string. The goal is to parse it as an Array inst ...