How to Accept jQuery Autocomplete White Spaces in Search Box

Autocomplete White Space

To accept white spaces in jQuery Autocomplete, you have to modify both client jQuery codes and server PHP codes.

On the client side

If you are using $.get() or $.getJSON() to get the source, you don't have to escape() or encodeURI() the input data, jQuery will encode the input data of GET method automatically.

$(function() {
  ...
  $("#bird").autocomplete({
    source : function(request, response) {
      $.getJSON("search.php", {
        query : request.term
      }, response);
    },
    minLength : 2,
    ...
  });
  ...
});

Otherwise, you'd be better to encode the input data first, if you are using $.post().

$(function() {
  ...
  $("#bird").autocomplete({
    source : function(request, response) {
      $.post("search.php", {
        query : encodeURI(request.term)
      }, response, "json");
    },
    minLength : 2,
    ...
  });
  ...
});

On the server side

You have to decode the input data before using it. Take PHP as an example:

<?php
...
$query = urldecode($_GET['query']);
...
?>

Now, the native request parameter term of jQuery Autocomplete will be able to respond to the input containing white spaces (blank spaces) or special characters.


If you want to link other pages on click or select, you may refer to this post: How to Link Pages in jQuery Autocomplete on Click or Select.

Further reading: How to Display jQuery Autocomplete Images in Results

Leave a Reply

Your email address will not be published. Required fields are marked *