How can I display a table value based on the selection from a dropdown?

I want to display (on an input text field) the description of a product (which is a MEDIUM TEXT field type) based on the selection of a dropdown containing the product ID. The tricky part is that I want to query my database by the product ID.

I'm able to display the product description on an input text field using Javascript but I want to query my database by the product ID.

I have a very simple database: product_ID | product_descrip "product_descrip" is a MEDIUM TEXT field type and can contains up to 16Mb for each product.

My CONTROLLER:

public function findProduct() {
    $products = Product::All();

    return view("updatingStock", compact("products"));
  }

public function stockUpdate(Request $req) {

  $selectedProduct = Product::where("product_ID", "=", $req["productsOption1"])->first();

  $selectedProduct->update();

  return redirect("/updatingStock");
}

My VIEW:

<select class="form-control" name="productsOption1" id="dropdown1">
      <option value="" selected>Product...</option>
    @foreach ($products as $product)
      <option value={{$product["product_descrip"}}>{{$product["product_ID"]}}</option>;
    @endforeach
  </select>

<input class="form-control" id="myproduct" type="text" placeholder=""  readonly>

MY SCRIPT:

<script type="text/javascript">
            var oneproduct = document.getElementById('myproduct1');
            var mydropdown = document.getElementById('dropdown1');

            mydropdown.onchange = function(){
                  myproduct.value = this.value;
            }
        </script>

As you can see, I'm able to display the product description on the input readonly field but I need to query my database by product_ID, not by product_descrip

Thanks a ton!

1 answer

  • answered 2019-09-16 03:31 Rao

    you can convert you records in to JS jsonobject and loop through it

    First return the rseult with view

    $selectedProduct = Product::where("product_ID", "=", $req["productsOption1"])->get();
     return redirect("/updatingStock")
    ->with('selectedProduct ',$selectedProduct );
    

    Then in js

     var mydropdown = document.getElementById('dropdown1');
     var Products = {!!json_encode($selectedProduct  -> toArray()) !!};
     var id= mydropdown.value;
    
     if (Products .hasOwnProperty(id)) {
         myproduct.value = this.productDescription;
     }