Check out my latest project: Full Frontal JavaScript Conference

jQuery Tag Suggestion

If you're familiar with del.icio.us you will be familiar with the tag suggesting as-you-type support.

The reason why, I believe, the tagging works so well within del.icio.us is that it helps you create a subset of tags that you commonly use for different types of links. This way, it makes it easier to find tagged content later on. i.e. conversely if it didn't suggest links, it would be likely that you would have different variations or even spellings of the same tag on (what should be) grouped content.

So, in an effort to adopt this approach, I've created a jQuery plugin for tag suggestion.

Download jQuery tag suggestion

Download tag.js

The plugin has been tested with:

  • IE 7
  • Firefox 2
  • Safari 3
  • Opera 9

If anyone has any problems in any other browsers (or even these), I would appreciate the feedback.

Demonstration

View the tag suggestion demo

View the source for the demo

The demonstration shows off both the static based tags and the Ajax based tag suggestion. Although the tag sets are the same, be sure to open Firebug and check the Ajax hits in the second example.

Example code

Static example

Allows the input field to have their own set of tag suggestions.

$(function () {
  $('input.tagSuggest').tagSuggest({
    tags: ['javascript', 'js2', 'js', 'jquery', 'java']
  });
  $('#otherlanguages').tagSuggest({
    tags: ['applescript', 'php', 'perl', 'java']
  });
});

Static global example

setGlobalTags(['javascript', 'js2', 'js', 'jquery', 'java']);
$(function () {
  $('input.tagSuggest').tagSuggest();
});

Ajax example

$(function () {
  $('#tags').tagSuggest({
    url: '/tag-suggestion'
  });
});

Style

I would recommend the following styles for the suggested tags:

SPAN.tagMatches {
    margin-left: 10px;
}

SPAN.tagMatches SPAN {
    padding: 2px;
    margin-right: 4px;
    background-color: #0000AB;
    color: #fff;
    cursor: pointer;
}

Plugin parameters

All parameters are optional, so long as tags have been set via the setGlobalTags function.

  • delay - sets the delay between keyup and the request - can help throttle ajax requests, defaults to zero delay
  • matchClass - class applied to the suggestions, defaults to 'tagMatches'
  • separator - optional tag separator string, defaults to ' '
  • sort - boolean to force the sorted order of suggestions, defaults to false
  • tagContainer - the type of element uses to contain the suggestions, defaults to 'span'
  • tagWrap - the type of element the suggestions a wrapped in, defaults to 'span'
  • tags - array of tags specific to this instance of element matches, defaults to global tags
  • url - url to get suggestions, overrides any specifically set tags. Must return array of suggested tags as JSON

72 Responses to “jQuery Tag Suggestion”

  1. Hello Remy, I must say that I really like this plugin.

    But, I just open my firebug and every time I write a letter I get a 404 error and almost crash my firefox lol. I have not even tested the script locally but i think that must be a problem with the routes with wordpress.

    Oh well, keep up the good work and thx for sharing this. :)

  2. @Lino - my bad! I had the url pointing to the wrong place. Fixed now. Cheers!

  3. This is great! I was just looking for autocomplete-scripts for jQuery and didn't find anything I liked. Your script comes very close to perfect :)

    What I would like to add would be separating tags with different separators (like colons) and possibility to use arrow keys to navigate between available suggestions (and spacebar, tab or enter selects) á la YUI autocomplete. ( http://developer.yahoo.com/yui/autocomplete/ )

    Anyway, good work, keep it up! :)

  4. [...] jQuery Tag Suggestion If you’re familiar with del.icio.us you will be familiar with the tag suggesting as-you-type support. (tags: ajax del.icio.us javascript jquery plugin tag development km) [...]

  5. [...] 2.0 Remy Sharp has recently posted an entry on his blog about del.icio.us style tag suggestion using jQuery. If you've used del.icio.us then you're [...]

  6. [...] jQuery Tag Suggestion (tags: jquery) [...]

  7. Wonderful!! Just that I need! thanks!

  8. Good plugin, but it makes too many query ajax,
    Add a new parameter "delay" for query AJAX

    get it here
    http://jcnevado.googlepages.com/tag.js

  9. @Julio - thanks for the suggestion. I've added a delay flag, though a slightly different implementation than yours - I moved the setTimeout earlier on in the code.

    I would suggest to anyone thinking about using the tag plugin, to try keep the delay as low as you can handle, giving a much as possible a sense of 'real-time' for the user.

  10. Static example is ok. But ajax version does not work for me even when I use copy of your demo html file, jquery.js and tag.js. For testing purposes I use url to php file which has only one line: . But no suggested tags appear on typing. What I am doing wrong?

  11. @minde66 - I've just made the source code to the demo page available here:

    http://remysharp.com/downloads/tagging.php

    It uses a simple array to match the tags, but it should give you a good idea of what's being delivered to the page.

  12. Thanks Remy. My json array structure was wrong. Because I will use comma as tags separator instead of space, I will try to adjust your script, but it would be nice to have such parameter.

  13. Hello,
    First of all, i have to tell you that it is a great plugin. But i have noticed something. When i type the first letter of the word as a capital, it produces wrong results. For example. First word is "Outdoor", when i start to type the second word, it still sends "Outdoor" to the server. I am using IE7. It works perfectly with lowercase letters.

  14. Hi there, is there anyway to remove the already choosed tags from the suggestion list? Or.... make the suggestion with another style, if I click... remove it?

    Sry for bad english!
    Nice plugin, btw!

  15. @Leandro - short answer - not right now. However, it's good feedback, so when I've got a bit of spare time I'll make the changes. Check back in a week if that's cool?

  16. Hi Remy, tks for your reply.
    Good to hear that feature will be implemented.

    Btw, i was playing with your plugin and i think i found a bug. With you demo, (in ajax mode), type "a", then click "agile", next type "C" (uppercase) then click "Cocoa".... now, type "a" again: "Cocoa" still there...

    I don't think this is suppose to happen! :)
    Hugs!

  17. @Leandro - thanks for the detailed explanation of the bug. Another user mentioned it, but I couldn't replicate it - now I can - thanks!

    I'll be working to sort that out too. Cheers.

  18. If someone could help me, that would be awesome. I'm not able to get this to work with my array (as minde66 above). My array prints fine with a foreach and echo, but it's apparently not json_encode - ing correctly. The ajax version was working fine using the test list in your demo ($default_tags). So... if my array's fine and the script is working fine, it must be something with the JSON encoding. Any pointers? Here's my code (Wordpress). The second part is straight from your demo.

    $get_tags = get_tags();
    if (!empty($get_tags)) {
      $tags = array();
      foreach($get_tags as $tag) {
        $tag_name = $tag->name;
        $tags[] = $tag_name;
      }
    }
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && @$_GET['tag']) {
      $match = array();
      foreach ($tags as $tag) {
        if (stripos($tag, $_GET['tag']) === 0) {
            $match[] = $tag;
        }
      }
    
      echo json_encode($match);
    
      exit;
    }
  19. Remy, no problem...
    I kind of "fixed" the bug removing the ".toLowerCase()" methods at lines 37 and 79.

    I don't know if is the best way to do it. But is working now!
    Hugs!

  20. Nice work!

    I found useful to include a separator parameter to support multi words tags. And use ', ' instead of ' ' to separate tags.

    http://weblogs.manas.com.ar/bcardiff/wp-content/uploads/2008/02/tag-separatorparam.patch

    Also I would probably implement a filter to remove already selected tags by user.

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight