【问题标题】:How to create a searchable select option form in laravel blade如何在 laravel Blade 中创建可搜索的选择选项表单
【发布时间】:2021-08-05 15:25:29
【问题描述】:

我正在尝试构建一个带有可搜索选项的城市选择选项表单。到目前为止,我已经构建了这个,但是选择的数据没有被保存,我的代码仍然缺少搜索功能。

{!! Form::select('custom_field1', array('Delhi', 'Goa'), '1', ['class' => 'form-control', 'placeholder' => 'Select City']); !!}

原始代码

<div class="col-md-3">
    <div class="form-group">
        {!! Form::label('custom_field1', $contact_custom_field1 . ':') !!}
        {!! Form::text('custom_field1', null, ['class' => 'form-control', 'placeholder' => $contact_custom_field1]); !!}
    </div>

【问题讨论】:

    标签: php jquery laravel forms


    【解决方案1】:

    您可以使用&lt;input&gt;list 属性和&lt;datalist&gt; 来实现您想要仅使用html 做的事情

    <div class="col-md-3">
        <div class="form-group">
            <label for="custom_field1">{{ $contact_custom_field1 }}:</label>
            <input id="custom_field1" name="custom_field1" type="text" list="custom_field1_datalist" class="form-control" placeholder="{{ $contact_custom_field1 }}">
            <datalist id="custom_field1_datalist">
                <option>Delhi</option>
                <option>Goa</option>
            </datalist>
            <span id="error" class="text-danger"></span>
        </div>
    </div>
    

    允许传递任何文本输入,因此您需要进行一些额外的验证。

    $('#your-form-id').on('submit', e => {
        $('#error').empty();
        let form = $(e.target);
        let validOptions = form.find('#custom_field1_datalist option').map((key, option) => option.value).toArray();
        let customField1Value = form.find('input[name=custom_field1]').eq(0).val();
    
        // check if custom_field_1's value is in the datalist. If it's not, it's an invalid choice
        if ( !(validOptions.indexOf(customField1Value) > -1) ) {
            // show error
            $('#error').text('Invalid Choice');
            // prevent form submission (you should still validate in the backend)
            e.preventDefault();
        }
    });
    

    另外,由于您已使用 JQuery 标记标记此问题,因此您可以使用像 select2 这样的库并让它为您执行此操作。

    你只需要把它放在你的&lt;head&gt;标签中

    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    

    select2 类添加到您的选择中。

    <select name="custom_field1" class="form-control select2" placeholder="Select City" required>
        <option>Delhi</option>
        <option>Goa</option>
    </select>
    

    然后,在您的 javascript 中,将其添加到您的 $(document.ready(...) 块中。

    $(document).ready(function() {
        $('.select2').select2();
    });
    

    【讨论】:

    • 你太棒了,它成功了,我目前在 11 点,我可以回答,对不起
    • 我很高兴它成功了。别担心。我认为您仍然可以接受答案。
    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多