Here you go: http://www.spookandpuff.com/examples/tagEntry.html
The general gist is...
- Allow the user to type whatever in a text input
- When they push enter, check if the tag is new, and if so add the value as an item to the list.
- Add a 'remove' link to allow the tag to be deleted from the list.
- Allow the list of tags to be sent back to the server evenutally.
Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Free Tag Entry</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//The event handler for the input:
$('#tagEntry').keypress(function(event){
if (event.keyCode == '13') { //If Enter is pressed
var newTagName = $(this).attr('value');
//Clear the helper message:
$('#tagEntryHelper').text('');
//Check if the tag exists already:
if (
!$('#addedTags > li > .tagName').filter(function(){
return $(this).text() == newTagName;
}).length
) {
//If not, add the value to the list of tags:
$('#addedTags').prepend('<li><input type="checkbox" name="tagName" value="' + newTagName + '" checked="checked"/><span class="tagName">' + newTagName + '</span> <a href="#" class="remove">Remove</a></li>');
} else {
//Tell the user they messed up:
$('#tagEntryHelper').text('You already added that tag.');
};
//Clear the input ready for the next tag
$(this).attr('value', '');
}
});
//The event handler for removing tags via a 'remove' link/icon (live is used so it works on newly added tags):
$('#addedTags .remove').live('click', function(){
$(this).closest('li').remove();
return false;
});
//An event handler for removing tags via unchecking a box
$('#addedTags :checkbox').live('change', function(){
if ($(this).not(':checked')) {
$(this).closest('li').remove();
return false;
}
})
});
</script>
</head>
<body>
<input id="tagEntry" type="text"/> <span id="tagEntryHelper"></span>
<ul id="addedTags">
</ul>
</body>
</html>
This works, though I have used some jQuery conventions which make the code easier to read, but are probably not the best in terms of performance. Unless you're expecting users to be working with thousands of tags, I wouldn't worry though - it should be fine.
I have included a checkbox in the tag list - assuming that eventually, you're going to want to post the contents of the list back to the server (probably as part of a form). You can hide these checkboxes with CSS if you don't want them visible, or, you can use them as the delete mechanism if you like. Either way, because all the checkboxes are named the same, your form will post back a comma separated list of tags (which should be easy to deal with at the server side).
Have a look at the demo - is that what you want?