Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alphabay84's avatar

Laravel fill form on autocomplete select

Hello all Please i need help with auto complete on select to fill form, the autocomplete is working and getting products from the database but i need to fill input form with product name, price etc. Please i need help with this, I have included below the following

<div class="container-fluid p-0 ">
    <label for="productName" class="sr-only">Поиск:</label>
    <input type="text" class="form-control input-sm rounded-0 border-0 pt-2" id="productName" placeholder="Поиск: Название товара">
            </div>

for search product (this works ok)

<div class="container-fluid p-0 border-top">
    <h4 class="text-center">Форма редактирования вносимых данных о товаре</h4>
    
<form action="#">
    
<input type="hidden" id="product-id">
    <div class="row">
    <div class="form-group col-6">

    <label for="product-name">Название товара:</label>
    <input type="text" class="form-control rounded-0 border-left-0" id="product-name" disabled>

    <label for="product-quantity">Количество:</label>
    <input type="number" class="form-control rounded-0 border-left-0 e-invalid" id="product-quantity" min="0" step="0.001" pattern="\d{1,2}[.|,]\d{3}$" title="Введите правильно значение!"  max="1000000">
    </div>

<div class="form-group col-6">
    <label for="product-purchase-price">Цена закупки:</label>
    <input type="number" class="form-control rounded-0 border-right-0 e-invalid" id="product-purchase-price" min="0" max="1000000000">

<label for="product-selling-price">Цена продажи:</label>
<input type="number" class="form-control rounded-0 border-right-0 e-invalid" id="product-selling-price" min="0" max="1000000000">
</div>

</div>
<div class="container-fluid d-flex justify-content-end p-0">
<button type="reset" class="btn btn-primary rounded-0" id="saveToCheck">Сохранить в чек</button>
</div>

</form>
</div>

this is the form where i want to fill on autocomplete select

        $(document).ready(function() {
            src = "{{ route('agent.searchajax') }}";
            $("#productName").autocomplete({
                source: function(request, response) {
                    $.ajax({
                        url: src,
                        dataType: "json",
                        data: {
                            term : request.term
                        },
                        success: function(data) {
                            response(data);

                        }
                    });
                },
                minLength: 1,

            });
        });
</script>

this is the JS for the auto complete this also work

    public function autoComplete(Request $request) {
        $query = $request->get('term','');

        $products=Product::where('name','LIKE','%'.$query.'%')->get();

        $result=array();
        foreach ($products as $product) {
            $result[]=array('value'=>$product->name,'id'=>$product->id);
        }
        if(count($result))
            return $result;
        else
            return ['value'=>'продукт не найден','id'=>''];
    }

this is the function for search in controller, this also works ok

Route::get('searchajax',array('as'=>'searchajax','uses'=>'AgentController@autoComplete'));

this the route

Please what i want to achieve is to fill the form with product details on autocomplete select, I have tried some tutorials and script but no success yet, thanks in advance

0 likes
4 replies
vajid's avatar

You are doing autocomplete for one product, so use first instead of get

$product = Product::where('name','LIKE','%'.$query.'%')->first();
$data= [
    'product-purchase-price' => '',
    // all other fields you want to auto fill
    // for simplicity use same id as input field id
];
if ($product) {
$data['product-purchase-price'] = $product->price;
//and so on
}

return response()->json($data);

and in js you can loop through response data, get key name find input // here key will be id of input tag

//something like this

    $('#'+key).val(value);

alphabay84's avatar

@VAJID Thanks for answer, i updated controller, for JS i do not understand how do i append on autocomplete click, cos when search done there are list of matching product then when a product is selected how do i append input values in the form. Please can do example for one input i.e name, price or quantity. Thanks

vajid's avatar
vajid
Best Answer
Level 3

You can use select function of autocomplete

http://api.jqueryui.com/autocomplete/#event-select

get the id, fetch the data

//in controller
function getSelectedProduct($id)
{
    $product = Product::findOrFail($id);
    return response()->json($product->toArray());
}

// in js
//ajax function
success:function(response)
{
    var product = JSON.parse(response);
    $('#product-purchase-price).val(product.price);
    // other field
}
alphabay84's avatar

@VAJID - thanks again, i think i get the idea. I will paste code when resolved

Please or to participate in this conversation.