PHPackages                             webcito/jquery-select-suggest - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. webcito/jquery-select-suggest

ActiveLibrary

webcito/jquery-select-suggest
=============================

Bootstrap-powered jQuery dropdown for server-side suggestions (typeahead with selectable items).

1.1.4(3mo ago)0142MIT

Since Jun 24Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/ThomasDev-de/jquery-bs-suggest)[ Packagist](https://packagist.org/packages/webcito/jquery-select-suggest)[ Docs](https://github.com/webcito/jquery-select-suggest)[ RSS](/packages/webcito-jquery-select-suggest/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (26)Used By (0)

jquery-selectSuggest
====================

[](#jquery-selectsuggest)

Create a Bootstrap-powered jQuery dropdown for server-side suggestions (typeahead with selectable items). Works with a simple HTTP endpoint returning JSON.

[![demo picture](./demo/selectSuggest-Demo.png)](./demo/selectSuggest-Demo.png)

### Table of contents

[](#table-of-contents)

- [Overview](#overview)
- [Stack and requirements](#stack-and-requirements)
- [Installation (CDN and self-hosted)](#installation-cdn-and-self-hosted)
- [Installation via Composer](#installation-via-composer)
- [Usage](#usage)
    - [html](#html)
    - [javascript](#javascript)
- [Options](#options)
- [Methods](#methods)
- [Events](#events)
- [Required response for suggestion](#required-response-for-suggestion)
- [Backend example](#backend-example)
- [Examples for multiple display](#examples-for-multiple-display)
- [Scripts](#scripts)
- [Environment variables](#environment-variables)
- [Run the demo locally](#run-the-demo-locally)
- [Tests](#tests)
- [Project structure](#project-structure)
- [License](#license)
- [Changelog](#changelog)

### Overview

[](#overview)

`jquery-selectSuggest` enhances a text input to fetch and display suggestions from your backend and lets users pick one or many items. It ships as a single jQuery plugin with no custom CSS — it reuses Bootstrap utilities and components.

### Stack and requirements

[](#stack-and-requirements)

- Language: JavaScript (jQuery plugin)
- UI framework: Bootstrap
    - Recommended: Bootstrap 5.x
    - Note: Bootstrap 4 may work, but is not actively verified here. TODO: confirm Bootstrap 4 compatibility.
- jQuery: developed and tested with 3.6.x (earlier versions not verified)
- Optional: Bootstrap Icons (for the small remove "x" inside the widget)
- Demo backend: PHP 8.0+ (only required for the example in `demo/`)

### Installation (CDN and self-hosted)

[](#installation-cdn-and-self-hosted)

No additional CSS is required; Bootstrap classes are used.

CDN example (Bootstrap 5 + jQuery + optional Bootstrap Icons):

```

```

CDN for the plugin itself:

- jsDelivr (GitHub): ```

    ```

    Note: If your release tag is named differently (e.g. `v1.1.1`), adjust the `@1.1.1` segment accordingly.
- When published to npm, you can also use:
    - jsDelivr (npm): `https://cdn.jsdelivr.net/npm/@webcito/jquery-select-suggest@1.1.1/dist/jquery.bsSelectSuggest.min.js`
    - unpkg: `https://unpkg.com/@webcito/jquery-select-suggest@1.1.1/dist/jquery.bsSelectSuggest.min.js`

Self-hosted (no CDN):

```

```

### Installation via Composer

[](#installation-via-composer)

Composer is not required to use the plugin in the browser. The JavaScript you need lives in `dist/`. In this repository, Composer is primarily used for the PHP demo to fetch Bootstrap and jQuery into `vendor/` (see “Run the demo locally”).

If you still want to manage this plugin in a PHP project via Composer, you have two options:

1. Packagist (when available)

- TODO: Publish the package to Packagist.
- Expected package name (per `composer.json`): `webcito/jquery-select-suggest`.
- Once published, install with:

```
composer require webcito/jquery-select-suggest
```

- After installation, copy or symlink the browser assets from `vendor/webcito/jquery-select-suggest/dist/` into your public web directory and include them in your HTML:

```

```

2. VCS repository (use this Git repo directly)

- Add a VCS repository entry to your project’s `composer.json` and require the package by name:

```
{
  "repositories": [
    {
      "type": "vcs",
      "url": "https://github.com/REPO_OWNER/jquery-bs-suggest"
    }
  ],
  "require": {
    "webcito/jquery-select-suggest": "^1.1"
  }
}
```

Replace `https://github.com/REPO_OWNER/jquery-bs-suggest` with the actual Git repository URL of this project.

- Then run:

```
composer update webcito/jquery-select-suggest
```

- As with Packagist, include the built file from `vendor/webcito/jquery-select-suggest/dist/` in your HTML.

Notes

- Composer does not automatically wire front-end assets. You must publish/copy/symlink the files in `dist/` to a web-accessible location (or reference them directly from your server’s vendor path if appropriate).
- If you do not want Composer at all, simply copy `dist/jquery.bsSelectSuggest.min.js` into your project and include it as shown in Installation above.

### Usage

[](#usage)

##### html

[](#html)

Place the input field where you want the dropdown to appear.

```

```

##### javascript

[](#javascript)

```
$('[data-bs-toggle="suggest"]').suggest(options);
```

Quick start example (full page):

```

    selectSuggest demo

      $(function(){
        $('#exampleInput').suggest({ limit: 10, multiple: false });
      });

```

### Options

[](#options)

Minimal, clear options grouped by purpose.

```
let options = {
  // Behavior
  limit: 10,                 // max number of records per request
  loadDataOnShow: true,      // load first page on open
  typingInterval: 400,       // debounce between keyup and request
  multiple: false,           // allow multiple selection
  selected: null,            // preselection on init; single: scalar, multiple: array of ids

  // Button
  btnWidth: 'fit-content',   // CSS width value for the trigger button
  btnClass: 'btn btn-outline-secondary',

  // UI texts (translations) — compact schema since 1.1.1
  translations: {
    search: 'Search',
    placeholder: 'Please choose..',            // alias: emptyText/btnEmptyText (deprecated)
    waiting: 'Waiting for typing',
    typing: 'typing..',
    loading: 'Loading..',
    clear: 'Clear',
    close: 'Close'
  },

  // Icons (HTML strings)
  icons: {
    remove: '',
    clear:  '',
    close:  '',
    // New in 1.1.1: dropdown selection indicators (no colored backgrounds)
    checked: '',
    unchecked: ''
  },

  // Data shaping
  queryParams: function(params){ return params; },

  // Rendering (suggestion list)
  formatItem: function(item){
    // Default renderer (you can override). For rich content the server may provide item.formatted.
    const sub = item.subtext ? `${item.subtext}` : '';
    return `${item.text}${sub}`;
  },

  // Header action labels next to icons (off by default)
  showHeaderActionText: false
}
```

Notes:

- Legacy names are still accepted and mapped internally to the new schema:
    - `emptyText`/`btnEmptyText` → `translations.placeholder`
    - `searchPlaceholderText` → `translations.search`
    - `waitingForTypingText` → `translations.waiting`
    - `typingText` → `translations.typing`
    - `loadingText` → `translations.loading`
    - `headerClearText` → `translations.clear`
    - `headerCloseText` → `translations.close`
- In `multiple: true` mode, the hidden input value is an array. For form submissions, use a field name with brackets, e.g. `name="country_id[]"` to receive an array server‑side.

Preselection with `selected`:

- If `selected` is defined and not null/empty, the plugin will immediately resolve those ids via the backend and set the selection on init (no `change` event is fired for this initial hydrate).
- Single select: pass a scalar (string/number). Example: `selected: 1`.
- Multiple select: pass an array of ids (strings/numbers). Example: `selected: [1, 3]`.

Rendering model:

- Suggestion list items use `formatItem(item)` (or the server‑provided `formatted` HTML when present) to render rich content.
- Button content:
    - Single select (`multiple: false`): renders rich HTML too. Preference order: `item.formatted` (when provided) → `options.formatItem(item)` (when provided) → the built‑in `formatItem(item)`. No inline remove control in single mode.
    - Multiple select (`multiple: true`): shows neutral, border‑only chips for each selected item, with an inline remove control per item. Chips are text‑only; they do not use `formatItem`.
- The built‑in default `formatItem` renders a modern, clean chip/tile with optional subtext (using only Bootstrap 5 utility classes). Override `formatItem` to control the suggestion list appearance; in single mode this will also affect the button when no `formatted` field is provided by the server.

Styling and theme compatibility:

- The dropdown uses only Bootstrap utility classes; no custom CSS and no styling options are required. It respects light/dark themes and different button variants.
- Selected items in the dropdown menu no longer rely on colored backgrounds; instead, a trailing icon indicates state (`icons.checked`/`icons.unchecked`).

Multiple button layout:

- `showMultipleAsList` (boolean): Controls how selected items are laid out inside the button when `multiple: true`.
    - `true` (default): vertical stack (`d-flex flex-column align-items-start`).
    - `false`: floating/wrapping layout (`d-flex flex-wrap align-items-center gap-1`). The plugin also relaxes some block utilities (e.g. converts `w-100` to `w-auto`) for a tighter inline look.

Dropdown header actions (to avoid ambiguous "x"):

- The header shows Clear and Close actions by default (icons only). You can customize labels via `translations.clear` and `translations.close`, and toggle labels via `showHeaderActionText`.
    - Behavior:
    - Clear resets only the current selection and keeps the current search and results list intact (dropdown stays open).
    - Close hides the dropdown.
    - Keyboard: Enter/Space on these buttons trigger the respective action.
    - Backward compatibility: the previous `.js-webcito-reset` control maps to Clear.

Removal from selection (multiple mode):

- Each selected item shown in the button includes a small remove control ("x"). The inline remove is only present in `multiple: true` and is hidden when the widget is disabled.
- Clicking it removes that item from the selection, updates the hidden input array, re-renders the button, syncs the active state in the dropdown, and triggers `change.bs.suggest` with `([ids], [items])`.
- For best visuals, include Bootstrap Icons: ```

    ```

Deprecated (backward compatibility):

- `multipleBadgeClass`, `formatBadge` are deprecated and ignored — use `formatItem`.
- Removed/cleaned options: `menuClass`, `density`, `menuMaxHeight`, `showCheckmark`, `checkIconHtml`, `highlightQuery`, `headerClass`, `searchInputClass`, `itemClass`, `activeItemClass`, `headerActionMode`.
    - If `debug: true`, the plugin logs a warning when any of these are provided. Use `icons` for icon customization, `translations` for texts, and `formatItem` for list content.

### Methods

[](#methods)

```
$('selector')
    .suggest('val', value) // set a value
    .suggest('refresh')  // build the dropdown new
    .suggest('destroy')  // destroy the dropdown
    .suggest('updateOptions', newOptions)  // update options
    .suggest('setDisabled', true|false);  // toggle disable class

$('selector').suggest('getSelectedText')
```

### Events

[](#events)

```
$('selector')
    .on('change.bs.suggest', function(e, a, b){
        // Single select: a = id, b = text
        // Multiple select: a = array of ids, b = array of full item objects
        console.log('change', a, b);
    })
    .on('error.bs.suggest', function(e, message){
        console.log('error', message);
    })
```

### Required response for suggestion

[](#required-response-for-suggestion)

The parameters `q` and `limit` are sent to the server via `GET`. `q` is in this case the search string and `limit` the maximum number of records to be determined. As response the plugin expects an `array` with `items` and the `total` number of records.
An item consists of the attributes `id` and `text`. Optionally you can provide:

- `subtext` (string) — a secondary line that the default renderer shows smaller below the main text (suggestion list only).
- `formatted` (string, HTML) — if present and non-empty, the plugin will render this HTML directly in the suggestion list, bypassing `formatItem`. In single select mode the button also prefers `formatted`; in multiple mode the button uses text‑only chips and ignores `formatted`.

```
{
  "items": [
    { "id": 1, "text": "Germany", "subtext": "EU, Schengen" },
    { "id": 2, "text": "Spain" },
    { "id": 3, "text": "Italy", "formatted": "ItalyPopulation ~60M" }
  ],
  "total": 75
}
```

When the method `val` is called, only the parameter `value` is sent to the server.
For single select the server should return a single item object.
For multiple select the server will send `value[]` as an array of IDs (jQuery serializes arrays like this) and expects an array in `items`. The optional fields `subtext` and `formatted` are supported here as well — if `formatted` is provided, it is used directly for the suggestion list. In single select mode, the button also prefers `formatted`/`formatItem`; in multiple mode the button uses text‑only chips.

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

```
{ "items": [ {"id": 1, "text": "Germany"}, {"id": 3, "text": "Italy", "formatted": "Italy"} ] }
```

### backend example

[](#backend-example)

A complete example can be found in the demo folder.

```
