Code Monkey home page Code Monkey logo

bootstrap-tokenfield's Introduction

Bootstrap Tokenfield

A jQuery tagging / tokenizer input plugin for Twitter's Bootstrap, by the guys from Sliptree

Check out the demo and docs

This project is no longer maintained!

Installation

Requirements: jQuery 1.9+, Bootstrap 3+ (only CSS)

  1. Install via npm or bower (recommended) or manually download the package
  2. Include dist/bootstrap-tokenfield.js or dist/bootstrap-tokenfield.min.js in your HTML
  3. Include dist/css/bootstrap-tokenfield.css in your HTML

Usage

$('input').tokenfield()

Features

  • Copy & paste tokens with Ctrl+C and Ctrl+V
  • Keyboard navigation, delete tokens with keyboard (arrow keys, Shift + arrow keys)
  • Select specific tokens with Ctrl + click and Shift + click
  • Twitter Typeahead and jQuery UI Autocomplete support

FAQ

How can I prevent duplicate tokens from being entered?

You can use the tokenfield:createtoken event for that. Check the event.attrs property for token value and label, and the run your duplicate detection logic. If it's a duplicate token, simply do event.preventDefault().

Here's a simple example that checks if token's value is equal to any of the existing tokens' values.

$('#my-tokenfield').on('tokenfield:createtoken', function (event) {
	var existingTokens = $(this).tokenfield('getTokens');
	$.each(existingTokens, function(index, token) {
		if (token.value === event.attrs.value)
			event.preventDefault();
	});
});

And how about limiting tokens to my typeahead/autocomplete data?

Similarly, using tokenfield:createtoken, you can check to see if a token exists in your autocomplete/typeahead data. This example checks if the given token already exists and stops its entry if it doesn't.

$('#my-tokenfield').on('tokenfield:createtoken', function (event) {
	var available_tokens = bloodhound_tokens.index.datums
	var exists = true;
	$.each(available_tokens, function(index, token) {
		if (token.value === event.attrs.value)
			exists = false;
	});
	if(exists === true)
		event.preventDefault();
})

Changelog

See release notes

Previous releases:

0.10.0

  • Fixed: Entering a duplicate token does not submit the underlying form anymore
  • Fixed: Selecting a duplicate token from autocomplete or typeahead suggestions no longer clears the input
  • Improved: Trying to enter a duplicate tag now animates the existing tag for a little while
  • Improved: Tokenfield input has now autocomplete="off" to prevent browser-specific autocomplete suggestions
  • Changed: triggerKeys has been renamed to delimiter and accepts a single or an array of characters instead of character codes.

0.9.9-1

  • Fixed: setTokens now respects triggerKeys option

0.9.8

  • New: triggerKeys option
  • Fixed: Long placeholders are not being cut off anymore when initializing tokenfield with no tokens #37
  • Fixed: createTokensOnBlur no more breaks token editing #35

0.9.7 Valuable

  • Fixed: Twitter Typeahead valueKey support #18
  • Fixed: Removing multiple tokens returned wrong data #30
  • Fixed: If token is removed in beforeEdit event, no longer falls over #27, #28
  • Fixed: Change event was triggered on initialization #22
  • Fixed: When token is removed in tokenfield:preparetoken event, no longer tries to create a token
  • Fixed: Pressing comma key was not handled reliably
  • New: prevetDuplicateToken event
  • Improved: Typeahead integration
  • Improved: styling
  • Minor tweaks, fixes, improvements

0.9.5 Typeable

  • New: Twitter Typeahead support
  • New: When triggering 'change' event on original input, setTokens is now called. This allows you to update tokens externally.
  • Fixed: Nnput labels did not work with tokenfield
  • Fixed: Set correct input width on fixed-width inputs

0.9.2 Maintenance release

  • Many small fixes and improvements

0.9.0 Bootstrappable

  • New: Bootstrap 3 support
  • New: Input group support
  • New: Disable/enable tokenfield
  • New: Tokenfield is now responsive
  • Deprecated: Bootstrap 2 support

0.7.1

  • Fixed: pressing comma did not create a token in Firefox
  • Fixed: tokenfield('getTokensList') returned array instead of string

0.7.0 Autocompleted

  • New feature: jQuery UI Autocomplete support

0.6.7 Crossable

  • Fixed: Firefox close icon was misplaced
  • New: IE 8-10 support (both CSS and Javascript)

0.6.5 Shiftable

  • New feature: select specific tokens with Ctrl/Shift + click
  • New feature: select specific tokens with Shift + arrow keys
  • Internal API improvements

0.6 Editable

  • New feature: Edit existing tokens by double-clicking or pressing enter
  • A lot of improvements and bugfixes

0.5 Initial release

bootstrap-tokenfield's People

Contributors

aries-ua avatar asacarter avatar brauliobo avatar breakoutbox avatar dmitrygusev avatar eduardoj avatar elplatt avatar fedesoria avatar haprog avatar igaponov avatar jonathanza avatar kamilgrzegorczyk avatar maduhaime avatar mattybearbytes avatar olegus8 avatar paxswill avatar powerman avatar ragulka avatar rcwsr avatar seangay avatar taivo avatar tmorehouse avatar varunkumar avatar xificurk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bootstrap-tokenfield's Issues

Using jQuery UI is not consistent with Twitter Bootstrap styles

jQuery UI Autocomplete doesn't fit well with Bootstrap's style. The typeahead dropdowns should be consistent with Bootstrap dropdowns style. I suggest adding an option typeahead similar to autocomplete which would use the Twitter Typeahead plugin instead of jQuery UI Autocomplete.

Restrict input to Typeahead

Feature Request or perhaps just misunderstanding the docs, but is there a way that the input can be restricted to only what is selected from the (bootstrap) typeahead? Not wanting invalid inputs to get included.

Token validation

User should be able to provide a validate method that will be used to validate the token just before creating it. If the validation fails, the token may either be created, but formatted differently, or prevented from being created in the first place.

Removing multiple tokens at once returns invalid token object into removeToken event

deleting multiple tokens at once gives the following token object in removeToken event:

{
    value: "value of the last token in a set of tokens", 
    label: "concatenated labels of all tokens in a set"} 
}

To fix this getTokenData should do something like this:

    getTokenData: function(token) {
      var $token;
      return token.map(function() {
              $token = $(this);
              return {
                  value: $token.data('value') || $token.find('.token-label').text(),
                  label: $token.find('.token-label').text()
              }
          }).get();
    }

Also getTokens method should be changed to:

getTokens: function(active) {
      var self = this
        , tokens = []
        , activeClass = active ? '.active' : '' // get active tokens only
      this.$wrapper.find( '.token' + activeClass ).each( function() {
        tokens.push( self.getTokenData( $(this) )[0] )
      })
      return tokens
  }

FireFox problematic support

I love tokenfield, thank you for it. Yet I see problems in FireFox - it doesn't add new 'tag' when pressing comma. Also if user types in a new tag, like if there is [one] [two] [three] and I type 'four' without pressing comma or enter, then .tokenfield('getTokensList') returns only the first three, not all four. I would assume it returns all four, even those which are not 'converted' from text to tag.

I hope you can fix this. I'm willing to spend some money on this, just let me know! :) Thanks

Add input group support

Seems like there is an issue with grouping styles. If I want to append a tag icon to the input field which gets tokenfield'ed (see bootstrap input groups), then the appended icon is wrong.

Check for duplicates incorrect

Check for duplicates should be done after "beforeCreateToken" cause after this event token data can be changed and if so the previous duplicates check is not valid.

typeahead data not getting updated

After adding one or more tags, we would want to update the typeahead with latest set of values which we get separately.

But when we try to reinitialise the typeahead it does not get updated

For example if we call the below lines, the data from 1st call only is used and not the second set

$('#seltags').tokenfield({
typeahead: {
valueKey: 'tag',
local:$scope.devicetags,
engine: Hogan
},
allowDuplicates: false
});

$('#seltags').tokenfield({
typeahead: {
valueKey: 'tag',
local:$scope.newdevicetags,
engine: Hogan
},
allowDuplicates: false
});

Here is a jsfiddle with the problem
http://jsfiddle.net/Srisudhir/yDzbf/1/

I was expecting that the type ahead would give me green, red in typeahead but it is giving me only blue, white

Suggested Functions

loved the plugin, thank you so much!

  1. How would I check to see if the token I'm about to create exist in the source and if not insert it into the source of the tokens?
  2. when I use create token it only append in the text box but not into the source of the tokens
  3. Is there a destroy function?
  4. I'm clearing the tokens (in the text box, not the source) with jQuery, is there a clear function?

Thank you so much!

Listen to original input changes

Tokenfield should setTokens when original input triggers change. This allows other plugins (e.g. Knockout) to update the original input and Tokenfield to reflect the changes accordingly.

missing docs

Hello, thanks for the great new release! :)
I think createTokensOnBlur is missing in documentation. It works though.

I would like to kindly ask you to document also how to access the input element itself to attach own events on blur or click for example. I used $('#tags').data('tokenfield').$input.val() for example, but this throws an exception now (Cannot read property '$input' of undefined). Will be great if this can be documented too.

Thank you very much!

Limit number of tokens in a field

Hi there,
Is it possible to limit number of tokens in a field? I couldn't find it in documentation.

Thanks.

P.S. I like this tokenfield. It's the best I have found on the internet. Simple and fast.
Great job.

Use Value as value instead of Label - Display Label instead!

Hello, I am using the typeahead as below

            $("#tokenfield-typeahead").tokenfield({
                typeahead: {
                    name: 'tags',
                    remote: {
                        url: SOMEURL
                    },
                    valueKey: 'name',
                    template: '<p class="">{{name}}</p>',
                    engine: Hogan
                }
            });

Now, I want to save the data-value as the value from JSON and display the selected value as the name from the JSON

The json comes as

[{"name":"Name","value":"VALUE"},{"name":"Name","value":"VALUE"},{"name":"Name","value":"VALUE"},{"name":"Name","value":"VALUE"}]

I wish that in the dropdown the name is displayed and when selected in the box also the name should be displayed but the actual value saved in the data-value attributed should be the value field from the JSON.

Any pointers?

Long placeholders are cut off until an initial token is added.

The following will result in a tokenfield which will have the placeholder cut off.

<input type="text" placeholder="This is maybe possibly questionably unknowingly not working just a bit correctly." />
<script>
$(':input').tokenfield({allowDuplicates: true, createTokensOnBlur: true})
</script>

Upon adding a token, the placeholder will behave normally.

createTokensOnBlur breaks token editing

set "createTokensOnBlur" to true. Add some tokens, with input focused dblclick a token to edit it. The token you dblclicked is replaced with an input but cause of "blur" event is triggered earlier then "dblclick" event it causes all tokens to be re-rendered so the token you're trying to edit is again in a list of tokens.

bootstrap-tokenfield.css: fix validation border

You current implementation doesn't handle validation border correctly - when field with tokens inside .has-error receive focus then border around input became blue instead of red plus inner input used to enter tokens get red border - so we've wide blue border around small red border - two border on same (visually) input.

Fix is to move border styles from tokenfield-typeahead.css .has-error .twitter-typeahead .tt-* to bootstrap-tokenfield.css .has-error .tokenfield.focus - you can see example implementation here: powerman/bootswatch@d6b42c0

Also I make .less version of your .css to make it easier to generate .css for custom bootstrap theme - if you like this idea you can take them from my repository (conversion probably isn't complete, but works for me and can be used as starting point).

Comma with space

If I type in some tags, like "apple, orange, banana", then tokenfield-ed input usually doesn't catch me pressing the comma key ",", because I type it very fast, thus I am releasing the comma AFTER pressing the space key:

  1. comma key is pressed (is typed in, but tokenfield doesn't tokenize tags)
  2. space key is pressed (space is typed in, tokenfield still doesn't tokenize tags)
  3. comma key is released, still no tokenized tags
  4. space key is released, still no tokenized tags.

This way I can type in many comma separated tags without them being tokenized at all.

It seems like you're monitoring keyUp event, I think we should monitor comma keyDown event rather than keyUp. Just a guess. Thank you

Tokens wrapper

It would be grate to have div wrapper for tokens for styling purposes. Ex., limit max-height of tokens wrapper but input should always be visible.

Workaround:

// line 42
    // Create a wrapper
    this.$wrapper = $('<div class="tokenfield form-control" />')
    this.$tokensWrapper = $('<div class="tokens-wrapper" />').appendTo(this.$wrapper)

// line 171
      var token = $('<div class="token" />')
            .attr('data-value', value)
            .append('<span class="token-label" />')
            .append('<a href="#" class="close" tabindex="-1">&times;</a>')
            .appendTo(this.$tokensWrapper)

//      // Insert token into HTML
//      if (this.$input.hasClass('tt-query')) {
//        this.$input.parent().before( token )
//      } else {
//        this.$input.before( token )
//      }

// line 398
var prev = this.$input.hasClass('tt-query') ? this.$input.parent().prev().find('.token:last') : this.$input.prev().find('.token:last')

Drag/drop to reorder tokens

Thanks for the awesome work! It would be great if it was possible to reorder the tokens by dragging and dropping them within the field...

Add Bootstrap 3 support

I noticed that bootstrap-tokenfield doesn't work very well with bootstrap 3, for example the width of tokenfield input doesn't update properly in row divs using bootstrap 3, probably because it uses class="col-sm-" instead of class="span" ? Or maybe the issue is there also with bootstrap 2? I didn't test that, I assume it's just a problem of bootstrap 3

Also the height of input field in bootstrap 3 seems to be different than the height set by tokenfield.

Is there any plan to support bootstrap 3 ?
Thank you very much

Create new token on custom key

It would be great to have a possibility to set a key code on which to create a token. For example if I have a field for e-mails I'd like to have tokens created on space key press.
I've added the following to make it work.

line 482

case 9: // tab
case 13: // enter
case this.options.createTokenOnKey: // custom set

line 888

$.fn.tokenfield.defaults = {
    minWidth: 60,
    minLength: 0,
    allowDuplicates: false,
    autocomplete: {},
    typeahead: {},
    showAutocompleteOnFocus: false,
    createTokensOnBlur: false,
    createTokenOnKey: null
  }

Duplicate tags submits form

If duplicate tags aren't allowed, when using a horizontal form then the form is submitted when pressing enter the accept try to accept a duplicate tag

Strange things

Hello, I am having issues with tokenfield.
When an input field is tokenfield-ed, it changes height.
See here:
http://jsfiddle.net/A4UJ7/2/
Click the button to see the height of tags input is changed. That shouldn't happen.

Furthermore I have one more problem.
After the tags input field is tokenfield-ed at the example above, remove the tag by clicking the X or by Delete key. You will see that while the tags input has still focus, you can notice the tags icon (right at the left of the input field) has few pixels on the left side missing. Something is probably covering it incorrectly. Hope you can see it too.

Thank you

Selecting with Bootstrap Typeahead: Enter key works but not clicking

Odd issue where a token lookup from a dynamic source using the bootstrap typeahead (not the jQuery one) only lets me choose a value by hitting the ENTER key. Clicking on the item doesn't do anything other than close the typeahead results.

I don't see the "beforeCreateToken" or "afterCreateToken" event firing at all.

data propagate

I use tokenfield in a way like

.tokenfield({
    'typeahead':{
        name: 'some-name',
        valueKey:'name',
        prefetch: {
            url:'/api/some-name',
            filter:function(objects){
                $(objects).each(function(index, object){
                    object.tokens = object.name.match(/[^ -_]+/g);
                });
                return objects;
            }
        }
    }
})

/api/some-name returns dataset like [{'name':'Isaak Newton','id':'1'},{'name':'Albert Einstein','id':'2'}], so you see, why I define object.tokens.

I want to use object.id then to populate some hidden input in a form. How can I do that?

getTokens doesn't return array

Hello, it seems that $('#tags').tokenfield('getTokens') doesn't return array as I would expect. It returns the original input element object.

Sort Tokens by Label instead of Value

Using a JSON object with value (int ID) and a label (string) and the tokens are automatically sorting by the value.

Any way to toggle the sorting?

Can not remove last tag

When removing the LAST token/tag, the ajax call is not working. With firebug, not http request is happening. Other tags/token can be correctly removed.

beforeCreateToken prevent Create

Is there a way that the creation of a token can be prevented in the beforeCreateToken event?

eg, If we want to inspect the value/label to decide whether the creation should proceed.

Add custom parameter on create

Hi, thank you for this plugin.

it's possible to add a custom parameter like this

$('input').tokenfield('createToken', { value : 'Value', label: 'Label', creation : 'auto' });

Note the custom parameter 'creation'.

Thank you!

tokenfield-typeahead.css needs vertical-align

You set .twitter-typeahead to display: inline-block and this result in some side-effects (for example, extra margin below input noticeable in multiline .form-horizontal configured to have no space between rows with inputs using .form-group {margin-bottom: 0;}).

Anyway, it's recommended to always use inline-block with vertical-align:

.twitter-typeahead {
  vertical-align: top;
}

RTL layout

If the form-group element has

direction:rtl;
text-align:right;

then the width of the token-input is miss-calculated and starts of narrow and get wider as you add tags.

Also also the styles for the inputs need to be
right: -10000px (instead of left)
when using an RTL layout

Write tests

It would be great if we can cover the existing functionality with tests. If anyone is willing to contribute, I am all ears!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.