Skip to content

Ajax and Enter #6398

Open
Open

Description

@ylmz-12

Hi;

I'm encountering a problem while using select2. What I want is for it to find the data I type in the search box in the database, and if it can't find it, to create a new label.

However, when I use AJAX and receive a "no results found" error, I can't use the Enter key. If it finds at least one result, it creates a new label, but if it doesn't find any results, the Enter key doesn't work. Labels are only created if I have defined "tokenSeparators" and press those keys.

Thank you for your support.

Activity

  1. sridharkalaibala commented on Sep 13, 2026

    @sridharkalaibala

    Enter can create a tag when an AJAX request succeeds with an empty result list. I tested this minimal setup in Chromium with the current Select2 bundle:

    <select id="tags" multiple></select>
    $('#tags').select2({
      tags: true,
      ajax: {
        url: '/search',
        dataType: 'json'
      }
    });

    For a search with no matches, /search returns HTTP 200 with:

    {"results":[]}

    Typing new-label then pressing Enter selected a newly created option with value new-label in the test; no tokenSeparators were configured.

    A successful search with zero matches is different from a failed HTTP request or an invalid response shape. If your endpoint uses another shape, processResults needs to return an object with a results array. A custom createTag callback can also suppress the proposed tag by returning null.

    Could you share your Select2 initialization and the Network-panel status/JSON response for a search with no matches? This would help distinguish a response/configuration issue from a keyboard bug. The test above creates the selected option in the browser; saving that new label to your database is a separate application step.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions