`Displaying the Quantity of Items Depending on the Product Chosen in Laravel Version 11`

How can I dynamically display the quantity of items from the 'item_amount' column when a product name is selected from the 'item_name' dropdown menu in Laravel 11, based on the data stored in the database?

Database

id item_code item_name item_amount
1 001 Pena 67
2 003 Palu 45

item.blade.php

    <!-- another code -->
    <div class="form-group">
        <label for="item_name" class="col-sm-4 control-label">Pilih Barang</label>
        <div class="col-sm-12">
            <select class="form-control" id="item_name" name="item_name" required>
                <option value="" disabled selected>Pilih Barang</option>
                @foreach($item as $i)
                    <option value="{{ $i->id }}">{{ $i->item_name }}</option>
                @endforeach
            </select>
        </div>
    </div>
    <div class="form-group">
        <label for="item-amount" class="col-sm-5 control-label">Jumlah Barang Tersedia</label>
        <div class="col-sm-12">
            {{ $item->item_amount }}
        </div>
    </div>
    <!-- another code -->

DemandController

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $demand = Demand::select('*');

            return DataTables::of($demand)
                ->addIndexColumn()
                ->addColumn('action', function ($row) {
                    $edit_btn = '<button ' .
                    ' class="btn btn-info" ' .
                    ' onclick="editItem(' . $row->id . ')">Ubah' .
                    '</button> ';
                    $del_btn = '<button ' .
                    ' class="btn btn-danger" ' .
                    ' onclick="deleteItem(' . $row->id . ')">Hapus' .
                    '</button> ';
                    return $edit_btn . $del_btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        $item = Item::all();
        $item_amount = Item::select('item_amount')->get();
        return view('demand', compact('item', 'item_amount'));
    }

Models/Item

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;

    class Item extends Model
    {
        use HasFactory;

        protected $table = 'item';

        protected $fillable = [
            'item_code', 'item_name', 'item_amount', 'item_unit', 'item_department'
        ];

        public function supplies()
        {
            return $this->hasMany(Supply::class);
        }

        public function demands()
        {
            return $this->hasMany(Demand::class);
        }
    }

Models/Demand.php

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;

    class Demand extends Model
    {
        use HasFactory;
        protected $table = 'demand';
        protected $fillable = [
            'item_id', 'user_id', 'sent_out', 'is_verify'
        ];

        public function item()
        {
            return $this->belongsTo(Item::class);
        }

        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }

routes/web.php

    <?php

    use App\Http\Controllers\DemandController;
    use App\Http\Controllers\ItemController;
    use App\Http\Controllers\RecruitmentsController;
    use App\Http\Controllers\SupplyController;
    use App\Http\Controllers\UserController;
    use Illuminate\Support\Facades\Route;

    Route::get('/', function () {
        return view('welcome');
    });

    Route::resource('recruitments', RecruitmentsController::class);
    Route::resource('item', ItemController::class);
    Route::resource('demand', DemandController::class);
    Route::resource('supply', SupplyController::class);
    Route::resource('users', UserController::class);

Problem Statement

My issue lies in the lack of real-time updating and failure to match the database content.

I aim to have the 'item_amount' value automatically update in real-time upon selecting a product name from a dropdown selector, utilizing Laravel and AJAX for modal.

Answer №1

Implement a change event listener for the item_name input field using JavaScript. Upon triggering the event, make an asynchronous request to the server using either AJAX or Axios, passing along the item_name as a parameter. The server should query the items table and retrieve the corresponding amount for the specified item. Once the request is successful, display the retrieved amount.

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

A guide on iterating through carousel elements using Vanilla JavaScript

I am currently extracting data from The Movie Database and I aim to showcase the retrieved information on my webpage using a carousel card with 3 slides. Here is a summary of my progress so far, html, <div class="details"><!--Movie deta ...

What is the best approach to generating nested JSON structures using Laravel and MySQL databases?

Can someone help me achieve the following structure? "results":[ { "id":1, "date":{ "date":"2015-04-1 00:00:00.000000", "timezone_type":3, "timezone":"America\/Denver" } }, This is my current query: ...

I'm intrigued: what type of syntax is Facebook's polling service utilizing in the callback?

While monitoring the Network Monitor on Chrome's developer tool, I observed how Facebook updates content on their news feed. All AJAX responses start with the following: for (;;);{"__ar":1,"payload":[]} I'm curious about what the for(;;); piec ...

Angular 2 FileReader: A comprehensive guide

I have a situation where I need to upload an image in section X and pass the base 64 data of the uploaded image to section Y. But I am encountering some difficulties in section X HTML: <input type="file" id="hotspot" (change)="uploadHotSpot($event)"&g ...

Could javascript be considered insufficient for conducting complex fluid simulations due to its speed limitations?

Currently, I am tackling the challenge of implementing a small fluid simulation in P5js. My attempt involved rendering 20,000 squares with random colors, but I only achieved a frame rate of 2.xxx. var sim; var xdim = 200; var xLength; var ydim = 100; var ...

How can I choose the div that is in the same container class div as this using Jquery?

As I cycle through data within a foreach loop, each iteration populates a container class as shown below: foreach($resultarray AS $value){ $filename = substr($value['img_file_name'],9); $cat_id = $value['cat_id']; ...

Using JQuery to parse data in a $.post request

My goal is to dynamically populate textboxes using JQuery based on an array sent from an external PHP file through json_encode(array). The chosen option in a select box determines which value is sent to the PHP file. Despite my efforts to debug using tools ...

The subscriber continues to run repeatedly, even after we have removed its subscription

The file brief-component.ts contains the following code where the drawer service is being called: this.assignDrawerService.showDrawer(parameter); In the file drawer-service.ts: private drawerSubject = new BehaviorSubject<boolean>(false); public ...

Updating a div using jQuery within a loop and showcasing all the values

I have implemented a foreach loop for the items in my cart. When I click on either the plus or remove buttons, the $value is updated correctly. However, I am seeing double the value in each row. Here is my script: <script type="text/javascript> ...

Discovering every element on a webpage

Searching for elements in a webpage can be done using different methods. document.getElementsByTagName('*') and document.all Are there any other more efficient ways or are these two the most recommended? I am currently working on an element se ...

jEditable: Reduce unnecessary AJAX calls by checking for changes in data before sending requests

Is there any concern with eliminating unnecessary ajax requests through optimization, such as the following: $('.editable').editable(function(value, settings) { // check if changed at all if(this.revert == value) { this.reset() ret ...

Extract information from a JavaScript function utilizing Python's Selenium

Is there a way to extract data from within a JavaScript function using Selenium? Visit the page here Here is the input code: <script type="text/javascript"> var chartData1 = []; var chartData2 = []; var chartData3 = []; ... ...

Leveraging Underscore in ReactJS applications

I'm encountering an issue with integrating Underscore into my ReactJS project. When I attempt to run my ReactJS class, the following error arises: Uncaught ReferenceError: _ is not defined index.html <html> <head> <meta http-equi ...

What is the best way to transform this unfamiliar CSS element into JavaScript code?

I'm facing an issue where I want to animate a CSS image based on time constraints, but since it's in CSS, I'm unable to achieve the desired effect. The animation in question is not the sun itself, but rather a yellowish half-circle animation ...

Using InnerHTML in Javascript within the Quasar/VueJS framework is unsupported

I am looking to dynamically create tables based on the items inside the 'counts' array below. The number of tables and their contents can change. Here is my divContainer, where the innerHTML will be appended: <div id="divContainer" style="pa ...

The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly. export class pdfService { formatter(value: number): string { return new Intl.N ...

Guide for saving and loading text data on an HTML file with JavaScript

I have a textarea and two buttons to save or open files. Here is the basic HTML structure: <form name="form1"> <textarea name="text1"> HTML Codes goes here </textarea> <input type="button"> Open File <input type="button"> Sa ...

Troubleshooting Ajax contact form's failure to refresh (PHP and Bootstrap 4)

I have successfully implemented this code on one website, but it is not working as expected on another website. It sends the email but refreshes the page and redirects to a contact.php page with a message. Despite double-checking everything, including cha ...

Unable to retrieve Celery task outcome in Django version 1.11

I am trying to retrieve Celery task results in Django using AJAX. Here is the view I have: def ajax_brand_count(request, task_id): extra_data = brand_count.AsyncResult(task_id) print("1", extra_data.state) print("2", extra_data.get()) if e ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...