Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS

I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts over several days, I have not been successful in finding a solution as I am relatively new to this.

WHAT I AIM TO ACHIEVE: I have two types of invoices: VendorInvoice and CustomerInvoice. After creating and storing data for a VendorInvoice in the database, I want to be able to autofill the same data into a CustomerInvoice. Essentially, upon selecting a VendorInvoice option from a dropdown list in the CustomerInvoice form, the fields should automatically populate with the corresponding details from the VendorInvoice and its items. This eliminates the need for manual data entry when creating a CustomerInvoice.

In my code:

VendorInvoice = ticketInvoice & VendorInvoiceItems = ticketInvoiceItems CustomerInvoice = ctInvoice & CustomerInvoiceItems = ctInvoiceItems

If anyone could assist me in resolving this issue, I would greatly appreciate it. Thank you.

This is the HTML <select> and some ctInvoice & ctInvoiceItems fields that I want to autofill:

<form @submit.prevent="editmode ? updateCtInvoice() : createCtInvoice()">
  <div class="modal-body">
    <div class="row">

      <!-- =====VENDOR INVOICE SELECTION===== -->
      <select id="ticket_invoice_no" v-model="selectedTicketInvoiceId" @change="getRecord" name="ticket_invoice_no" type="text" class="form-control">
        <option v-for="ticketInvoice in ticketInvoices" :key="ticketInvoice.id" :value="ticketInvoice.id">{{ ticketInvoice.ticket_invoice_no }}</option>
      </select>

      <!-- =====CUSTOMER TICKET INVOICE NUMBER===== -->
      <input v-model="form.ct_invoice_no" type="text" name="ct_invoice_no" class="form-control">

      <!-- =====CUSTOMER TICKET INVOICE ITEMS===== -->
      <tbody>
        <tr v-for="(ctInvoiceItem, key) in form.ctInvoiceItems" :key="key">
          <!--Passenger Name-->
          <td>
            <input v-model="ctInvoiceItem.ct_passenger_name" size="40" type="text" name="ct_passenger_name" class="table-control form-control">
          </td>

          <!--Ticket No.-->
          <td>
            <input v-model="ctInvoiceItem.ct_ticket_no" size="24" type="text" name="ct_ticket_no" class="table-control form-control">
          </td>

          <!--Flight No.-->
          <td>
            <input v-model="ctInvoiceItem.ct_flight_no" size="7" type="text" name="ct_flight_no" class="table-control form-control">
          </td>
      </tbody>

My @change="getRecord" method:

getRecord: function(e) {
  axios
    .get("api/ticket-invoice/fetch/" + this.selectedTicketInvoiceId)
    .then(({
      data
    }) => {
      console.log(data);
      this.form = data; // assumes the data keys maps directly to the form properties!!
    })
    .catch(error => {
      console.log(error.response);
    });
}

Route:

Route::get('ticket-invoice/fetch/{ticket_invoice}', 'API\TicketInvoiceController@fetch')->name('ticket-invoice.fetch');

My fetch(){} method:

public function fetch($id) {
  $ticketInvoices = TicketInvoice::findOrFail($id);

  return response() ->json([
    'id' => '',
    'customer_id' => '',
    'ct_invoice_no' => $ticketInvoices->ticket_invoice_no,
    'ct_invoice_date' => $ticketInvoices->ticket_invoice_date,
    'ct_invoice_fares_total' => $ticketInvoices->ticket_invoice_fares_total,
    'ct_invoice_grand_total' => $ticketInvoices->ticket_invoice_grand_total,
    'ctInvoiceItems' => $ticketInvoices->ticketInvoiceItems->map(function($item) {
      return [
        // get the relevant $item->property for each key below
        'id' => "",
        'ct_invoice_id' => "",
        'ct_passenger_name' => $item->passenger_name,
        'ct_fares' => $item->fares,
        'ct_sub_total' => $item->sub_total
      ];
    }) ->all()
  ]);
}

My data() in Vue Component:

data() {
  return {
    editmode: true,
    selectedTicketInvoiceId: false,
    ticketInvoices: {},
    ctInvoices: {},
    customers: null,
    form: new Form({
      id: "",
      customer_id: "",
      ct_invoice_no: "",
      ct_invoice_date: "",
      ct_invoice_fares_total: 0,
      ct_invoice_grand_total: 0,

      ctInvoiceItems: [{
        id: "",
        ct_invoice_id: "",
        ct_passenger_name: "",
        ct_fares: 0,
        ct_sub_total: 0
      }]
    })
  };
},

When I select an option, I can see the specific data filling in my Vue Component's respective id, but the input fields are not being populated with that data. Therefore, I am unable to make changes and eventually store the updated information in the database as a CustomerInvoice.

Vue Dev Tool BEFORE SELECTING OPTION: https://i.sstatic.net/5ztV8.png

Vue Dev Tool AFTER SELECTING OPTION: https://i.sstatic.net/ND867.png

BUT NOT FILLING FIELDS: https://i.sstatic.net/Q7spY.png

Answer №1

Although I may not be well-versed in Laravel 5.7 or vue, the fundamental concept remains consistent.

1- To illustrate my approach, I will create a PHP file that queries the database with a select * statement and outputs the result in JSON format.
2- Subsequently, I will utilize ajax or fetch to retrieve this JSON data from the PHP file, which can then be used in the corresponding JavaScript file.
3 - A function will be implemented such that upon clicking a dropdown option, data will be fetched through AJAX requests, updating the dropdown options accordingly.

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

The export of 'alpha' is not available in the '@mui/system' module

Help! I am encountering an error related to the @mui/material library. I have already looked into the package.json file of mui/system and it seems that 'alpha' is exported in it. ./node_modules/@mui/material/styles/index.js Attempted import erro ...

Steps for dynamically executing an Angular ng-include directive in real-time

Is there a way to dynamically insert an ng-include element into an HTML page and have it function properly? I am working on a Drag N Drop application where users can drag an element onto the page, and upon dropping it in the designated zone, the original ...

Node.js/Express/Jade scripts failing to load in the expected order

Imagine having this code snippet in a .jade file: doctype 5 html head title= title link(rel='stylesheet', href='/stylesheets/style.css') script(src='/javascripts/ocanvas-2.2.2.min.js', type='text/javascript') ...

How can I use JavaScript to create a drop-down menu that only appears after selecting the previous one?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id=" ...

Retrieve JSON data with Vue.js prior to rendering the page

I have a query about extracting JSON data objects and rendering them prior to mounting. Just to clarify, I am working in a standalone environment. I don't believe the issue lies with the function itself, but rather with the lifecycle aspect of it. I h ...

Angular2's $compile directive functions similarly to AngularJS 1's $compile directive

I am currently in the process of migrating my project from Angular 1 to Angular 2 and I am in need of a compile directive. However, I am struggling to rewrite it to achieve the same functionality as before. app.directive("compile", compile); compile.$inje ...

What is the process for changing the selected value after it has been clicked and removing the previous selection

Is there a way to change the class of a li element in a PHP view after it has been clicked? <ul> <li> <a href="<?=base_url()?>home" id="home" onclick="select_class('home');" class="shortcut-dashboard" title="Home">Home& ...

Attempting to change the primary color in Bootstrap is ineffective following a button click

I have been attempting to customize the primary color of Bootstrap 5 using SCSS. Everything works perfectly until I click a button that opens an external link. Below is the content of my SCSS file: $primary: #ae217aff; @import "../node_modules/boots ...

Passing form values from JavaScript to a JSP page - a comprehensive guide

I am working on a sample HTML page that includes inline JavaScript for calculating geocodes and retrieving latitude and longitude values. My question is, how can I submit all the form values along with the latitude and longitude returned from the showlocat ...

What is the process for loading an external file within an npm script?

Objective: Testing the linting process of specific components within the source code, without affecting all files. I want to streamline the linting process by running a single command that covers multiple folders specified in a configuration file: //pack ...

What provides quicker performance in AngularJS: a directive or one-time binding?

I need to display a static array on a webpage without Angular watching its value. With that requirement in mind, my question is: Which method is faster: using a directive to fetch a scope variable and create an HTML element with this variable as a hard-co ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

Removing a similar object from an array using JavaScript

Working on a d3 force graph, I aimed for smooth updates using the method shown in the Modifying a Force Layout example. However, my goal was to achieve dynamic updating behavior unlike the static example provided. After calling initializeGraphData(json); i ...

Customizing checkboxes in React with JSS: A step-by-step guide

I'm currently working on customizing CSS using JSS as my styling solution, which is proving to be a bit complex while following the w3schools tutorial. https://www.w3schools.com/howto/howto_css_custom_checkbox.asp HTML: <label class="container"& ...

Creating a canvas with multiple label introductions can be achieved by following these

I am looking to group labels and sublabels on the x-axis of a canvas component. Currently, I only have sublabels like: RTI_0, RTI_1... I would like to add labels to these sublabels like: RTI = {RTI_0,RTI_1,RTI_2] BB = {BB_0, BB_1,BB_2,BB_3] <div cla ...

Using the `preventDefault` method within an `onclick` function nested inside another `onclick

I am currently working on an example in react.js <Card onClick="(e)=>{e.preventDefault(); goPage()}"> <Card.body> <Media> <img width={64} height={64} className="mr-3" ...

Making a page jump with Javascript

Welcome! Let's dive into our question. Below you'll find my script and HTML code: My Script: const resultEl = document.querySelector('.allquotes'); const pageSize = document.querySelector('select[name="page-size"]') ...

Implementing dynamic width with ng-style in AngularJS

I am trying to dynamically resize a div when an event is fired from S3. In the code below, I pass the progress variable to the updateProgress function as a parameter. This function resides in the top scope of my Angular controller. s3.upload(params).on(& ...

Use the powerful $.post() method to transfer an image to another page seamlessly

I have two pages, the first page contains a form where users can enter information such as name and mobile number. Additionally, they can upload an image. I would like to use jQuery to access the uploaded image and send it to another page using the $.post( ...

What is the process for building a JSON-formatted dictionary?

My intention is to structure my data in a way that can be accessed using a specific key. The current arrangement looks like this: const dict = []; dict.push({"student": "Brian", "id":"01", "grade":& ...