Using Vue.js, pull information from a database to populate input fields using a datalist feature

I'm currently working on a project utilizing Laravel 8 and Vue 3, and I have a Student Component. Within this component, there is a datalist that allows me to search for existing students. When I select a student from the list, I want the corresponding data from my database to populate the fields.

I've attempted using vueJs and v-model, but I'm only able to retrieve the string in the input of the datalist. Additionally, when trying to retrieve the data, I encounter issues where I receive [object Object] in either the field or datalist input.

Here's a snippet of my code:

//This section contains the data of my trainees who are the students
 data() {
        return {
            trainees: [],
          },
          //This method is used to fetch the student details from the database
  methods: {
     getTrainee() {
            axios.get(AXIOS + 'trainee')
                .then(response => this.trainees = response.data)
                .catch(error => console.log(error));
        },
  },
<!--The following excerpt is part of my student component, featuring the datalist for finding students-->
 
 <div class="search_trainee">
            <input id="search" class="search_trainee_input" list="trainees" placeholder=" "
                   type="text">
            <label class="label_search" for="search">Search a trainee</label>
            <datalist  id="trainees">
                <option v-for="user in trainees" :key="user.id">
                    {{ user.firstname }} {{ user.lastname }}
                </option>
            </datalist>
        </div>

  <!--In another part of my Student component, I aim to auto-fill my fields with selected student data-->

        <div class="form_trainee">
            <h3 class=" title_form">Add a trainee</h3>
            <div class="row g-3">
                <div class="col-md-6">
                    <input id="lastname" ref="lastname" class="form-control" name="lastname" placeholder=" "
                           type="text" @blur.prevent="addTrainee();displayAudit()">
                    <label class="label_form" for="lastname">Lastname</label>
                </div>
                <div class="col-md-6">
                    <input id="firstname" ref="firstname" class="form-control" name="firstname" placeholder=" "
                           type="text" @blur.prevent="update">
                    <label class="label_form" for="firstname">Firstname</label>
                </div>
                <div class="col-md-6">
                    <input id="email" ref="email" class="form-control" name="email" placeholder=" " type="email"
                           @blur.prevent="update">
                    <label class="label_form" for="email">Email</label>

                </div>
                <div class="col-md-6">
                    <input id="company" ref="company" class="form-control" name="company" placeholder=" "
                           type="text"
                           @blur.prevent="update">
                    <label class="label_form" for="company">Company</label>

                </div>
                <div class="col-md-6">
                    <input id="vehicle" ref="vehicle" class="form-control" name="vehicle" placeholder=" "
                           type="text"
                           @blur.prevent="update">
                    <label class="label_form" for="vehicle">Vehicle</label>

                </div>
                <div class="col-md-6">
                    <input id="location" ref="location" class="form-control" name="location" placeholder=" "
                           type="text"
                           @blur.prevent="update">
                    <label class="label_form" for="location">Location</label>

                </div>
                <div class="col-md-6">
                    <select id="instructor_id" ref="instructor_id" v-model="instructor" class="form-control"
                            name="instructor_id"
                            @blur.prevent="update">
                        <option value="">--Choose an instructor--</option>
                        <option v-for="user in instructors" :key=user.id v-bind:value="{id:user.id}">{{
                                user.firstname
                            }}
                            {{ user.lastname }}
                        </option>
                    </select>
                </div>
                <div class="col-md-6">
                    <select id="acpCenter" ref="acp_center_id" v-model="acpCenter" class="form-control" name="acpCenter"
                            @blur.prevent="update">
                        <option value="">--Choose an Acp Center--</option>
                        <option v-for="center in acpCenters" :key="center.id" v-bind:value="{id:center.id}">
                            {{ center.city }} {{ center.postal_code }}
                        </option>
                    </select>
                </div>
            </div>
        </div>

If you have any advice, tips, or further assistance, please feel free to share. I can provide additional code if needed. Thank you for your time.

Answer №1

Vuejs does not support event handlers for datalist, making it challenging to achieve your desired outcome. Have you considered using vue-select? It's a user-friendly option with easy event handling capabilities.

Check out this demo:

Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: "#app",
  data() {
    return {
      selectedStudent: "",
      acpCenter: "",
      instructor: "",
      instructors: [
        { id: 10, firstname: "instructor1", lastname: "lastname" },
        { id: 11, firstname: "instructor2", lastname: "lastname" },
        { id: 12, firstname: "instructor3", lastname: "lastname" }
      ],
      acpCenters: [
        { id: 10, city: "city", postalCode: "postalCode" },
        { id: 11, city: "city2", postalCode: "postalCode" },
        { id: 12, city: "city3", postalCode: "postalCode" }
      ],
      trainees: []
    };
  },
  mounted() {
    this.getTrainee();
  },

...

</script>

Note that this is the browser version. To integrate it into your local nodejs project:
  1. yarn add vue-select or npm install vue-select to add the dependency
  2. import both the vue-select and css as shown below:
<script>
import Vue from "vue";
import vSelect from "vue-select";
import "vue-select/dist/vue-select.css";
Vue.component("v-select", vSelect);
</script>

The final code in your app.vue or something.vue file would resemble this:

<template>
  <div class="container">
    <div class="search_trainee">
      <v-select
        v-model="selectedStudent"
        @input="onInput"
        label="firstname"
        :options="trainees"
      ></v-select>
...

</script>

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

Implementing hover effect triggered by keyboard input

Is there a way to create a hover effect on a div when a specific key is pressed on the keyboard using jQuery? <div id="d-up" class="button"></div> Appreciate any help with this! Thank you. ...

How can ETags be utilized in fetching data?

To prevent mid-air collisions caused by multiple users or processes modifying the same item in the database, I am considering using Etags for validation. Here is my proposed approach: The client will call a RESTful API to obtain an Etag from the header, ...

Error: Improper hook call detected with no hooks being used (material-ui v5)

I've created the following basic application: import Grid from '@material-ui/core/Grid'; function App() { return ( <div className="App"> <Grid container spacing={2}> <Grid item xs={8}> ...

One thing to note is that eloquent eager loading does not fetch associated model information

In my Laravel project, I am working with two Eloquent Models, namely Set and Card, which have a one-to-many relationship between them. This means that a Set can have many Cards, and each Card belongs to a Set. When attempting to retrieve the data using El ...

Exploring Bootstrap datatables to search through nested table data with Codeigniter

I have implemented a table using bootstrap datatables and successfully enabled search functionality within the table. However, I have also included nested tables within each row of the main table. These nested tables are supposed to be displayed when clic ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

When using Node.js, res.render may encounter issues, but res.send typically functions properly

Currently, I am in the process of setting up the environment for a node.js app. Unfortunately, I am encountering an issue where the views/ejs files are not being rendered properly. When I use the following code snippet: app.get("/", function(req, res){ ...

In Laravel Inertia Vue JS, the page appears blank after adding the export default statement

In my current project, I have a component that utilizes PrimeVue Datatable and ConfirmDialog like so: <template> <Head title="Patients" /> <AppLayout> <template #header> <div class="p-2& ...

What steps should I take to resolve the issue of 'this.reduce() not being a function'?

Here is my code : app.get("/", (req, res) => { const reducer = (acc, guildCount) => acc + guildCount; const results = client.shard.fetchClientValues('guilds.cache.size'); console.log(results) let guildCount ...

Modifying data within a pre-set framework

Let's take a look at a basic setup for the task at hand: In the HTML Side test.html <div id="app"> <my-comp temp="1" cat="{ name:'Geoff', age:3 }"></my-comp> </div> Transitioning to the Vue Side app.js: impo ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Navigating through different tabs in an AngularJS application is made simple and efficient with the help of $

I used the angular-authentication-example to create a login page for my project. After logging in, the homepage should display multiple tabs just like in this example on Plunker. <ul class="nav nav-tabs" ng-controller="TabsCtrl"> <li ng-class= ...

How can we modify specific values of an object using Lodash and return the updated object?

const fruits = { apple: 2, orange: 3, grape: 4, banana: 5 } My aim is to adjust the values of certain fruits while being able to reference their current values. For example: const premiumFrutis = _.doSomething(fruits, apple + 2, banana + ...

retrieve a subdocument from an array in MongoDB

In my MongoDB database, I have the following data structure: {doc: { array_doc:[....//many documents]} } Currently, I am working with Mongoskin in MongoDB 2.2 with Node.js 0.8. var code_doc='HSKD41814541211'; var db = mongo.db(perm+"@127.0 ...

Avoiding ChartJS tooltips from being cut off

I've been exploring how to prevent chartjs from cutting off its tooltips, but I haven't been able to find a config option to address this issue. https://i.sstatic.net/Knzvd.png Here's what I've attempted so far: <script> ...

What is the best way to compare two times in the hh:mm AM/PM format?

I need to handle times in the format of hh:mm AM/PM generated by a specific plugin, and perform comparisons on them using jQuery/javascript. When a user manually inputs a time, I require the text in the textbox to automatically adjust to hh:mm AM/PM with ...

Unable to replicate the exact Bootstrap template found on their website

Attempting to replicate a template from bootstrap.com, but encountering issues with the copied version. The navigation bar is turning white instead of remaining black, and I'm unable to change the color. Additionally, facing problems with the toggle ...

What sets apart ajax calls from getJSON requests?

I am encountering an issue with my Web.API app being served from the URL http://server/application. When I try to pull data from the servers using a GET request on the client side, I am facing unexpected behavior. The following code snippet works as expec ...

Manipulating lines and positions with jQuery

I am looking to implement a feature that allows users to choose a specific region on an image using jQuery. The functionality should be similar to the tagging feature on Facebook, but with the added bonus of being able to rotate and scale the selected area ...

Exploring the process of sending post data and navigating to a URL using AngularJS

I am working on an application using angularjs 1.6 and Java 8. My goal is to send POST data to another application and navigate to the URL that this external application determines. The purpose of my application is to transmit data about a citizen who wan ...