Skip to content

Instantly share code, notes, and snippets.

@willishq
Created January 27, 2015 21:35
Show Gist options
  • Select an option

  • Save willishq/60d53448f33343ea25c0 to your computer and use it in GitHub Desktop.

Select an option

Save willishq/60d53448f33343ea25c0 to your computer and use it in GitHub Desktop.
Simple input tags jQuery snippet
Array.prototype.remove = function (value) {
return this.filter(function (element) {return element !== value});
};
var tags = [];
$('.tag-box').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
$('.tag-input', this).focus();
});
$('.tag-input').on('keyup', function (e) {
var tagvalue = '';
if (e.which == 13 || e.which == 9 || e.keyCode == 13 || e.keyCode == 9) {
e.preventDefault();
tagvalue = $(this).val().trim();
if (tagvalue === '') {
$(this).val('');
$(this).focus();
return false;
}
if (tags.indexOf(tagvalue) === -1) {
tags.push(tagvalue);
$('<span class="tag-item" data-value="' + tagvalue + '">' + tagvalue + '<i class="tag-remove fa fa-times"></i></span>').insertBefore(this);
} else {
$("[data-value=" + tagvalue + "]").animate({"padding": '0.6rem'}, 250, 'linear').animate({"padding": '0.4rem'}, 250, 'linear');
}
$(this).val('');
$(this).focus();
return false;
} else if (e.which == 8 || e.keyCode == 8) {
var $this = $(this);
var $prev = $this.prev();
if ($this.val() === '' && $prev.hasClass('tag-item')) {
if ($prev.hasClass('delete')) {
var value = $prev.data('value');
$this.val(value);
tags = tags.remove(value);
$prev.remove();
} else {
$prev.addClass('delete');
}
}
}
});
$('.tag-box').on('click', '.tag-remove', function () {
var $parent = $(this).parent();
var value = $parent.data('value');
tags = tags.remove(value);
$parent.remove();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment