webcito/jquery-select-suggest

1.0.0 2024-06-24 08:06 UTC

This package is auto-updated.

Last update: 2024-09-24 08:40:54 UTC


README

为服务器建议创建一个 Bootstrap 下拉菜单。

目录

demo picture

要求

  • Boostrap >= 5.0
  • jQuery 3.6 -> 我不能命名最低的 jQuery 版本,我是在 jQuery 3.6 上开发的。

安装

只需在 body 标签的末尾包含以下脚本。

<script src="/dist/jquery.bsSelectSuggest.js"></script>

不需要额外的 CSS,当前使用 bootstrap 类。

使用

html

将输入字段放在你想要下拉菜单出现的位置。

<input type="text"
       id="exampleInput"
       data-bs-toggle="suggest"
       data-bs-target="path/to/actions.php"
>
javascript
$('[data-bs-toggle="suggest"]').suggest(options);

选项

以下选项目前已实现。

let options = {
    "limit": 10, // the maximum number of records
    "loadDataOnShow": true, // Shows the first entries based on limit
    "typingInterval": 400, // The milliseconds to wait until a request starts
    "darkMenu": false, // show the dropdown in dark style
    "btnWidth": 'fit-content', // Corresponds to the CSS property width
    "btnClass": "btn btn-outline-secondary", // dropdown button class
    "emptyText": "Please choose..", // placeholder for no selection
    "searchPlaceholderText": "Search", // placeholder for search input
    "waitingForTypingText": "Waiting for typing", // Status
    "typingText": "typing..", // Status
    "loadingText": "Loading..", // Status
    "queryParams": function(params){return params} // add params to query
}

方法

$('selector')
    .suggest('val', value) // set a value
    .suggest('refresh')  // build the dropdown new
    .suggest('destroy')  // destroy the dropdown
    .suggest('updateOptions', newOptions);  // update options

事件

$('selector')
    .on('change', function(e, id, text){
        console.log(id, text, 'was selected');
    })
    .on('error', function(e, message){
        console.log('error', message);
    })

建议所需响应

参数 qlimit 通过 GET 发送到服务器。q 在这种情况下是搜索字符串,limit 是要确定的最大记录数。作为响应,插件期望一个包含 itemstotal 记录总数的 array
一个项目由属性 idtext 组成。

{
    "items": [{
        "id": 1,
        "text": "Germany"
      },{
        "id": 2,
        "text": "Spain"
      },{
        "id": 3,
        "text": "Italy"
      }
    ],
    "total": 75
}

当调用 val 方法时,只发送参数 value 到服务器
并且只期望 一个项目对象(不是数组)。

{
    "id": 1,
    "text": "Germany"
}

后端示例

一个完整的示例可以在演示文件夹中找到。

<?php
/**
 * Note: PHP8.0 or higher is required for this script.
 */
header('Content-Type: application/json');

try {
    // Fetch a test data set
    /** @var stdClass[] $countries */
    $countries = json_decode(file_get_contents('countries.json'), false, 512, JSON_THROW_ON_ERROR);

    // Try to find the query parameter value
    $value = filter_input(INPUT_GET, 'value', FILTER_VALIDATE_INT);

    /** @var null|stdClass|array $return */
    $return = null;

    // Was the value parameter found?
    $fetchSingleData = ! empty($value);

    // if yes
    if ($fetchSingleData)
    {
        // Get the record using the value parameter
        $data = array_values(array_filter($countries, static function($country) use ($value){
            return $country->id === $value;
        }));
        $return = $data[0];
    }
    // if no
    else
    {
        // Get parameter q and limit
        $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT);
        $q = filter_input(INPUT_GET, 'q');
        $search = empty($q)? false : strtolower($q);

        // If q was not passed or is empty, do not return any results either.
        // Otherwise, search for matches of the search string.
        $data = array_slice(
            array:array_values(array_filter($countries, static function($country) use ($search){
                return $search === false || str_contains(strtolower($country->text), $search);
            })),
            offset: 0,
            length: $limit
        );

        // Put the result in the response
        $return['items'] = $data;
        $return['total'] = count($countries);
    }
    // Return as JSON
    http_response_code(200);
    exit(json_encode($return, JSON_THROW_ON_ERROR));
} catch (JsonException $e) {
    http_response_code(500);
    exit(json_encode(['error' => $e->getMessage()], JSON_THROW_ON_ERROR));
}