How to Save Unmatched Text in a jQuery Select2 Dropdown with an AJAX Call
Tags: javascript, webdev, programming, tutorial
Published: 2023-01-03 12:30:25

jQuery Select2 is a powerful dropdown component that allows users to search for and select items from a list. It's easy to use and can be changed in many ways, making it a popular choice for web developers.

In this tutorial, we'll learn how to use a jQuery Select2 dropdown to search for text inside a database using an AJAX call. We'll also learn how to deal with the Enter key and save the text typed; into the database if there are no search results.

First, let's initialize the Select2 dropdown and set the AJAX call parameters:

```
$(document).ready(function() {
  // Initialize the Select2 dropdown
  $('#mySelect2').select2({
    // Set the AJAX call parameters
    ajax: {
      url: '/search',
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {
          q: params.term, // search term
          page: params.page
        };
      },
      processResults: function (data, params) {
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;

        return {
          results: data.items,
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },
      cache: true
    },
    minimumInputLength: 1,
    templateResult: formatRepo, // template for the results
    templateSelection: formatRepoSelection // template for the selected item
  });
});
```

In this code, we are using an AJAX call to search for text in a database. The **_minimumInputLength_** parameter is set to 1, so the AJAX call is only triggered when the user enters at least one character in the dropdown. We are also using **_templateResult_** and **_templateSelection_** to customize the display of the results and the selected item.

Next, let's figure out what to do when the Enter key is pressed and save the entered text to the database if no search results are found:

```
// Handle the Enter key press on the Select2 dropdown
$('#mySelect2').on('keypress', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode === 13) {
    // Get the entered text
    var text = $(this).val();

    // Check if there are no search results
    if ($('.select2-results__option--highlighted').length === 0) {
      // Save the text to the database via an AJAX call
      saveTextToDatabase(text);

      // Reset the Select2 dropdown
      $(this).val(null).trigger('change');
    }
  }
});

// Function to save the text to the database via an AJAX call
function saveTextToDatabase(text) {
  $.ajax({
    url: '/save',
    type: 'POST',
    data: {text: text},
    success: function(response) {
      console.log('Text saved to database: ' + text);
    },
    error: function(error) {
      console.log(error);
    }
  });
}
```
This may come in handy for adding new records to the database and ensuring that the list is always up to date. This functionality may be effortlessly added to any of our online applications with just a few lines of code.