基于Laravel中文本框自动完成的动态下拉选项

时间:2016-04-22 19:14:22

标签: jquery laravel dynamic dropdown

我正在使用Laravel,Jquery& MaterializeCSS。我的要求是根据文本输入自动完成填充表单中的下拉选项。我使用一个源文本自动完成,另一个源填充下拉列表。它是一个多选。从自动完成填充inoput字段后,下拉列表不会填充。如果我们在下拉列表上显示它没有显示任何内容,但是当我选择默认值时,其显示值显示在来自源的图像中。

After autocpmplete of text field

When selected option then its showing the city value

请帮助解决此问题。这是我的代码。

HTML:

   <div class="input-field col s12 m12 l4">
    {!! Form::label('company_w', 'Company') !!}
    {!! Form::text('company_w', null, ['class' => 'validate']) !!}
   <input id="company_id" name="company_id" type="hidden" />
</div>

<div class="input-field col s12 m6 l4">

        <select id="city_id" name="city_id" multiple>
        <option value="">--</option>
        </select>
</div>

的JScript:

        $(function() {
        $("#company_w").autocomplete({
            source: "companies/autocompletecompanies",
            minLength: 3,
            select: function (event, ui) {
                $('#company_w').val(ui.item.value);
                $('#company_id').val(ui.item.id);

                $.get("/companies/autocompletecompanycities",
                        {company_id: ui.item.id},
                        function (data, status) {

                            var model = $('#city_id');
                            model.empty();
                            $.each(data, function (index, element) {
                                model.append("<option value='"+ element.id +"'>" + element.name + "</option>");

                            });


                        });
            }


        });

    });

Controlelr:

    public function autocompleteCompanies(){
    $term = Input::get('term');

    $results = array();

    $queries = Companies::orderBy('name', 'asc')
        ->where('name', 'LIKE', $term.'%')
        ->take(5)->get();

    foreach ($queries as $query)
    {
        $results[] = [ 'id' => $query->id, 'value' => $query->name ];
    }
    return Response::json($results);
}

public function autocompleteCompanycities(){
    $term = Input::get('company_id');

    $cities = array();

    $company = Companies::findOrfail($term);

    $address = Addresses::with('cities')
             ->where('company_id', '=', $company->id)
             ->get();

    foreach($address as $addrs)
    {

        $cities[] = [ 'id' => $addrs->cities->id, 'name' => $addrs->cities->name];
    }
    return Response::json($cities);
}

1 个答案:

答案 0 :(得分:0)

我认为您需要使用Materialize.css脚本重新初始化选择框,在更新/销毁选择段落中阅读here

所以尝试做这个操作。

$.get("/companies/autocompletecompanycities",
        {company_id: ui.item.id},
        function (data, status) {

            var model = $('#city_id');
            model.empty();
            $.each(data, function (index, element) {
                model.append("<option value='"+ element.id +"'>" + element.name + "</option>");

            });

            model.material_select(); //refresh the dropdown
});