How To Build Tag Input Autocomplete Suggestions with Tokeninput


How To Build Tag Input Autocomplete Suggestions with Tokeninput

Featured image for How To Build Tag Input Autocomplete Suggestions with Tokeninput
Tag-based input fields are becoming more common amongst social networks. Also consider new applications such as user-submitted news which provide another method for predefined tags. There are other plugins available which display tag choices in a formatted list using a typical input field.
But in this tutorial I want to showcase how we can include autocomplete suggestions generated from a list of JSON queries. I will be using the jQuery Tokeninput plugin which is free and open source to use within any project. This plugin only works with a set of predefined tags in a list, so it isn’t the perfect solution. But it does help when you need to limit user selection since it can pull results from a database via AJAX.
tokeinput autocomplete suggestions input preview tutorial screenshot

Getting Started

First we need to download a copy of the plugin files to copy over into your working directory. I have made two new folders by the names /js/ and /css/ which will contain some new files along with some plugin codes. Copy over the token-input.css and token-input-facebook.css stylesheets into your CSS folder. I’ve also made a new styles.css file which is specific to this tutorial demo.
<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Tag Input Suggestions with Tokeninput - SpyreStudios Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://spyrestudios.com/favicon.ico">
  <link rel="icon" href="http://spyrestudios.com/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <link rel="stylesheet" type="text/css" media="all" href="css/token-input.css">
  <link rel="stylesheet" type="text/css" media="all" href="css/token-input-facebook.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/jquery.tokeninput.js"></script>
</head>
You will notice we need to include a copy of the JS plugin file itself, along with a copy of the jQuery library. The dependencies can grow quickly but much of the CSS could also be merged into a single file. Especially if you plan to overwrite these files and customize the default input design.
    <div id="searchbar">
      <input type="text" id="vidyagames" name="vidya">
    </div>
Now the inner body text is fairly simple because I have only included a single form input element. This can be used for toggling the suggestions which are highlighted based on input by the user. Results will be limited down as the user types in more characters, and once a tag is selected it then becomes an item in the field which is then passed into the form on submit.

Page Styles

There are not a whole lot of customized settings aside from page resets and the default wrapper. I have included a copy of Henny Penny from Google Webfonts. Also the repeating background image Natural Paper is courtesy of Subtle Patterns.
/* page structure */
#wrapper {
  display: block;
  width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 35px 22px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-box-shadow: 1px 2px 1px rgba(0,0,0,0.4);
  -moz-box-shadow: 1px 2px 1px rgba(0,0,0,0.4);
  box-shadow: 1px 1px 2px rgba(0,0,0,0.4);
}

#searchbar {
  display: block;
  padding: 15px 0px;
}


/* custom settings */
.token-input-token-facebook p { font-size: 1.0em; color: #555; }
.token-input-selected-token-facebook p { color: #fff; }
Considering the page itself is really focused on a single input field, I do not need a whole bunch of customized settings. The wrapper itself is neatly fitted into the page along with the input field. Of course we could add many extra fields to display this page as a full submission form, but for the sake of this tutorial it is easier to focus on complexity in the scripting.
You’ll also notice at the very bottom I have cleared some room for additional styles. Each inner tag element appears as a paragraph tag within the input display. The selector .token-input-token-facebook p is resetting the font size on each internal tag while the code beneath this is targeting a currently-selected tag. In this case the background turns darker blue yet the text also stays dark, so I’m forcing it to appear white so that it’s readable.
If you want to learn more about overwriting styles just look through the plugin stylesheets. I have noticed many selectors inside token-input-facebook.css are easy to read and easy to customize as well.

Frontend Scripting

Because I don’t have a database setup it is easier for me to include the JSON tag options right within the JavaScript. If your list is also like this you might want to move these codes into a separate .js file. Notably it would be easier to create a simple backend script in PHP or Ruby to handle a database connection with JSON response. You can read more about this on the plugin documentation page.
$(function(){
  $('#vidyagames').tokenInput([
      {id: 7, name: "Super Mario"},
      {id: 11, name: "Battletoads"},
      {id: 13, name: "Pong"},
      {id: 17, name: "The Legend of Zelda"},
      {id: 19, name: "Metroid"},
      {id: 23, name: "Donkey Kong Country"},
      {id: 29, name: "Super Smash Bros."},
      {id: 32, name: "Star Fox"},
      {id: 35, name: "Starcraft"},
      {id: 37, name: "Pokemon"},
      {id: 38, name: "Minecraft"},
      {id: 41, name: "The Sims"},
      {id: 43, name: "Final Fantasy"},
      {id: 44, name: "Resident Evil"},
      {id: 46, name: "Kingdom Hearts"},
      {id: 47, name: "Tetris"},
      {id: 48, name: "Grand Theft Auto"},
      {id: 51, name: "World of Warcraft"},
      {id: 53, name: "Metal Gear Solid"},
      {id: 54, name: "Civilization"},
      {id: 56, name: "Pac-Man"},
      {id: 59, name: "Animal Crossing"},
      {id: 62, name: "Spyro the Dragon"},
      {id: 64, name: "Crash Bandicoot"},
      {id: 65, name: "Sonic the Hedgehog"},
      {id: 72, name: "Tomb Raider"},
      {id: 77, name: "Mortal Kombat"},
      {id: 81, name: "Space Invaders"}
    ], { 
      theme: "facebook",
      hintText: "Know of any cool games?",
      noResultsText: "Nothin' found.",
      searchingText: "Gaming...",
      preventDuplicates: true
  }); 

});
Because I am listing the entire JSON string within the function call I needed to include the list inside square brackets first. This separates the list into a different notation compared to the curly brace options. The query tag ID values may be randomized but it’s meant to retain value from the ID of a database object. Though it won’t really matter unless you are handling the form submission on the backend.
By passing the theme name as “facebook” our plugin will now locate the alternate CSS file as the base stylesheet. It changes class names and provides a quick method for customization. The other options relate to the labels which are displayed at various times during the interaction. The very last option I have added for preventDuplicates basically stops any user from including the same tag twice.
There is plenty of reason to use this duplicate option because nobody wants form submissions with 2 or 3 of the same tags. Also this is not a full list of options and you can check out a lot more from the documentation. But this plugin offers so much functionality and it doesn’t make sense to cram it all into one demonstration. Toy around with these options and see what kind of tagged form interface you can build.
tokeinput autocomplete suggestions input preview tutorial screenshot

Final Thoughts

This tutorial is a great method for developers to get into more customized form inputs. Granted only using a set of predefined tags is certainly not perfect. I certainly hope the plugin may expand to include additional choices in the future. Simply put, the Tokeninput plugin is quick to setup and the documentation page is easy to understand. If you have similar ideas or questions on the tutorial feel free to share in the post discussion area below.

Comments

Popular posts from this blog

รู้จักกับ Breakpoints ใน Responsive Web Design

IS-IS & OSPF

RIP Routing Information Protocol