Searchbox example

Info

This example shows how to implement a search box that will either give you autocomplete suggestions and redirect to the searchpage, or just redirect to the searchpage.

Dependencies for this example:

Resulting redirect

Show code ▼



If you haven't included loop54-js-lib already, include this part and configure it to talk to your loop54 proxy
<script type="text/javascript" src="loop54-js-lib.js"></script>
<script type="text/javascript">
  Loop54.setConfig({url: "https://helloworld.54proxy.se"}); // you will get this config from us when we have set up an engine
</script>
Then include the following function in a separate javascript file or last in your HTML body tag
<script type="text/javascript">
  var redirectSearch = function(event, query, facet) {
    var searchPageLocation = "http://d.loop54.com/"; // Change this to the URL or path of your searchpage. I.E. ("/search")
    if(document.location.pathname === searchPageLocation) { return; } // Prevent redirect if you are on the searchpage already
    if(event) {
      event.preventDefault();
      query = document.forms[event.target.id].search.value;
    }
    if(query.length > 1) {
      /*
      * This defines how you want a query to be formatted before sending,
      * we are using hash (#) by default but feel free to change it to questionmark (?) if that's what you prefer.
      */
      var redirectString = searchPageLocation + "#query=" + query;

      // This also adds a facet if that was choosen in autocomplete
      if(facet) { redirectString = redirectString + "&f=" + facet };

      document.location = redirectString; // Changing document.location will redirect the browser to the new location
    }
  }
</script>
Then choose which version of the searchbox you want to use, with or without autocomplete.

This first example is without autocomplete
<form id="searchForm" action="#" onsubmit="return false">
  <label for="search">Search</label>
  <input type="text" name="search" id="search" placeholder="Type something" />
  <button type="submit">Search</button>
</form>

<script type="text/javascript">
  document.getElementById("searchForm").addEventListener("submit", redirectSearch);
</script>
This example is with autocomplete
<head>
  <link rel="stylesheet" href="jquery-ui.min.css" />
</head>
<body>
  <form id="searchWithAutocompleteForm" action="#" onsubmit="return false">
    <label for="search-with-autocomplete">Search</label>
    <input type="text" name="search" id="search-with-autocomplete" placeholder="Type something" />
    <button type="submit">Search</button>
  </form>

  <script type="text/javascript" src="jquery-2.1.1.min.js"></script>
  <script type="text/javascript" src="jquery-ui.min.js"></script>
  <script type="text/javascript">
    document.getElementById("searchWithAutocompleteForm").addEventListener("submit", redirectSearch);

    var autocompleteCache = {};
    var autoCompletePageSize = 6;
    var autoCompleteQuest = "AutoComplete";
    $("#search-with-autocomplete").autocomplete({
      minLength: 2,
      source:  function(req, res) {

        var req,
        cache = autocompleteCache;

        if(autocompleteCache[req.term]) {
          var response = autocompleteCache[req.term];
          if(!response.success) {
            console.log(response.errorMessage);
          } else {
            var data = response.data;
            if(data.AutoComplete.length > 0) {
              res(formatData(data));
            } else {
              res([]);
            }
          }
        }
        req = {
          QuestName: autoCompleteQuest,
          QueryString: req.term,
        };
        if(autoCompletePageSize > 0) {
          req.autoComplete_FromIndex = 0;
          req.autoComplete_ToIndex = autoCompletePageSize;
        }
        Loop54.getResponse(req).then(function(response) {
          autocompleteCache[req.term] = response;
          if(!response.success) {
            console.log(response.errorMessage);
          } else {
            var data = response.data;
            if(data.AutoComplete.length > 0) {
              res(formatData(data));
            } else {
              res([]);
            }
          }
        });

      },
      select: function(event, ui) {
        event.preventDefault();
        event.stopPropagation();
        redirectSearch(null, ui.item.value, ui.item.facet);
      },
      open: function(event, ui) {
        // prevent iOS from first setting focus on menu items instead of triggering click event
        $(".ui-autocomplete").off("menufocus hover mouseover mouseenter");
      },
    });

    $("#search-with-autocomplete").autocomplete("instance")._renderMenu = function(ul, items) {
      var that = this;
      var facets = [], withoutFacets = [];
      facets = items.filter(function(item) {return item.facet ? true : false});
      if(facets.length > 0) { facets[facets.length-1]["lastFacetItem"] = true };
      withoutFacets = items.filter(function(item) {return item.facet ? false : true});
      items = facets.concat(withoutFacets);
      $.each(items, function(index, item) {
        that._renderItemData(ul, item);
      });
    };

    $("#search-with-autocomplete").autocomplete("instance")._renderItem = function(ul, item) {
      var label = item.value;
      if(item.facet) {
        label = item.value + " in " + "<span class=\"facet\">" + item.facet + "</span>";
      }
      return $("<li/>").addClass(item.lastFacetItem ? "last-facet-item" : null).append("<a>" + label + "</a>").appendTo(ul);
    };

    var formatData = function(data) {
      var ret, facets;
      ret = data.AutoComplete.map(function(x) {
        return {
          value: x.Key,
          label: x.Key,
        };
      });

      facets = data.AutoCompleteFacets.map(function(x) {
        return {
          label: data.AutoCompleteFacetingString,
          value: data.AutoCompleteFacetingString,
          facet: x.Key,
        };
      });

      ret = ret.concat(facets);
      return ret;
    }
  </script>
</body>