Nifty and FAST ‘Tags’ in the browser using JQuery, HTML, CSS, and JS

On one of my recent ASP.Net projects, I needed to enable a user to pick an arbitrary set of things from a long list and wanted to do this WITHOUT any round trips to the server.  Since it worked well I’d share it out!  Here’s what the simplified ‘Tags’ looks like:


In my project I used a JQuery Autocomplete box to enable the user pick the tag from a predefined (but very long) set – I’ve simplified down the code to make it easier to demo.  You can check this out using JSFiddle here:

Complete JSFiddle “Tag” Sample

The interesting bits of the JavaScript code are included below.  You can add in your own code for adding/removing tags (if you need to fire off other operations) and can add to the Submit code to process the tags before submitting the form back to the server.

function AddTag(element, failLabel, label, value) {
  // Let's only do a tag if the label has content
  if (label) {
    // we have to escape the label!  It could have quotes
    label = label.split("\"").join(""");
' + label + '


'); } } function RemoveTag(element) { $(element).parent().remove(); } $('#TagsInput') .bind("keydown", function(event) { if (event.keyCode == 13) { AddTag("#TagsUI", "#Alert", $('#TagsInput').val(), $('#TagsInput').val()); $('#TagsInput').val(''); } }) .blur(function() { AddTag("#TagsUI", "#Alert", $('#TagsInput').val(), $('#TagsInput').val()); $('#TagsInput').val(''); }); $('#Submit').click(function() { // here we process the tags var TagElements = $('#TagsUI').find('div'); var tags = []; for (i = 0; i < TagElements.length; i++) { tags.push($(TagElements[i]).attr("value")); } $('#Result').text(tags.join(';')); });

Hope you found this helpful!

Comments (0)

Skip to main content