Convert to tag as you type
by Terry King
HTML
<input name="" type="text" class="taginput"/>
CSS
.tagholder{
position:relative;
margin:0px;
padding:0px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
border: 1px solid #000;
}
.tagitem{
display:inline-block;
border: 1px solid #000;
background-color:#999;
padding:2px;
border-radius:2px;
margin-top: 2px;
margin-right: 2px;
margin-bottom: 2px;
margin-left: 2px;
}
.tagtext{
float:left;
position:relative;
padding:0px 4px 0px 4px;
margin:0px;
cursor:pointer;
}
.tagtext:hover{
background-color:#06F;
}
.tagclose{
font:Arial, Helvetica, sans-serif;
float:left;
position:relative;
padding:0px 2px 0px 2px;
margin:0px;
cursor:pointer;
}
.tagclose:hover{
background-color:#F00;
}
.taginput{
margin-left:0px;
margin-right:0px;
margin-top:0px;
margin-bottom:0px;
padding-left:0px;
padding-right:0px;
padding-top:0px;
padding-bottom:0px;
vertical-align: bottom;
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
}
.taginput:focus{
outline:none;
}
.taginputholder{
display:inline-block;
margin-left:0px;
margin-right:0px;
margin-top:0px;
margin-bottom:0px;
padding-left:2px;
padding-right:0px;
padding-top:10px;
padding-bottom:0px;
position:relative;
top:-5px;
}
JavaScript
function bindClose(){
$('.tagclose').unbind('click').click(function(){
li=$(this).parent();
console.log(li);
li.remove();
});
}
$('.taginput').keypress(function(e){
if (e.which==32 || e.which==13 || e.which==44){
$(this).parent().before('<div class="tagitem"><div class="tagtext">'+$(this).val()+'</div><div class="tagclose">x</div></div>');
$(this).val("");
bindClose();
}
});
$('.taginput').each(function()
{
$(this).wrap('<div class="tagholder"></div>');
$(this).wrap('<div class="taginputholder"></div');
});