This is a JQuery plugin for input tags with auto complete suggestion.

Overview

Jquery Suggestags

This is a JQuery plugin for input tags with auto complete suggestion.

$('input').amsifySuggestags();

npm installation

npm i suggestags

Table of Contents

  1. Simple
  2. Default Value
  3. Suggestions
  4. Suggestions Through Ajax
  5. White List
  6. Custom Stylings
  7. Callbacks and Events
  8. Tag Limit
  9. Refresh Destroy
  10. More Settings
  11. Instantiating

Simple Tags

For simple initialization

<input type="text" class="form-control" name="country"/>
$('input[name="country"]').amsifySuggestags();

Default Value

If input is already having value separated by comma, it will load the tags by default

<input type="text" class="form-control" name="country" value="India,UAE,Nepal"/>
$('input[name="country"]').amsifySuggestags();

Suggestions

List of values can be passed to get the suggestions.

<input type="text" class="form-control" name="country"/>
$('input[name="country"]').amsifySuggestags({
	suggestions: ['India', 'Pakistan', 'Nepal', 'UAE', 'Iran', 'Bangladesh']
});

List if objects can also be set to have tag/value pair.

<input type="text" class="form-control" name="color"/>
$('input[name="color"]').amsifySuggestags({
	suggestions: [
					{tag: 'Black', value: 1},
					{tag: 'White', value: 2},
					{tag: 'Red', value: 3},
					{tag: 'Blue', value: 4},
					{tag: 'Green', value: 5},
					{tag: 'Orange', value: 6}
				]
});

Input will store value separated by comma like this

<input type="text" class="form-control" name="1,2,3,4,5,6"/>

Note: While setting the default value for the input, set actual value separated by comma not tag names.

Suggestions Through Ajax

We can also get suggestions through Ajax

<input type="text" class="form-control" name="country"/>
$('input[name="country"]').amsifySuggestags({
	suggestionsAction : {
		url: 'http://www.site.com/suggestions'
	}
});

Ajax method type will be GET, structure of request data you will receive is

{
	"existing": ["one", "two", "three"],
	"term": "something"
}

existing is an array of already loaded tags and term is the string you are trying to search.
The success response should at least contain suggestions key and its value should be of type list/array:

{
	"suggestions": ["four", "five", "six"]
}



You can also add these settings and callbacks to this option

$('input[name="country"]').amsifySuggestags({
	suggestionsAction : {
		timeout: -1,
		minChars: 2,
		minChange: -1,
		delay: 100,
		type: 'GET',
		url: 'http://www.site.com/suggestions',
		dataType: null,
		beforeSend : function() {
			console.info('beforeSend');
		},
		success: function(data) {
			console.info('success');
		},
		error: function() {
			console.info('error');
		},
		complete: function(data) {
			console.info('complete');
		}
	}
});
timeout - It is for cancelling the request after given specific seconds, default is -1
minChars - It is the minimum chars types before the first ajax hit, default is 2
minChange - It recall the ajax based on the minimum percentage chars changed compared to the string passed in last ajax call, default is -1
delay - It is the milliseconds time delay to call ajax or whitelist suggestions on text entered and wait, defult is 100
type - It is type of method we pass, default is GET
dataType - It is dateType of request data being passed, default is null

Note: success and complete callbacks does not directly override the original ajax callbacks, rather it gets called after original ones are executed.

White List

This option simply does not allow any other inputs other than from suggestions.

<input type="text" class="form-control" name="country"/>
$('input[name="country"]').amsifySuggestags({
	suggestions: ['India', 'Pakistan', 'Nepal', 'UAE', 'Iran', 'Bangladesh'],
	whiteList: true
});

Custom Stylings

<input type="text" class="form-control" name="country"/>

For setting default class for tags, you can pass this setting

$('input[name="country"]').amsifySuggestags({
	suggestions: ['India', 'Pakistan', 'Nepal', 'UAE', 'Iran', 'Bangladesh'],
	whiteList: true,
	defaultTagClass: 'badge'
});

We can pass list of classes, colors or backgrounds through settings

$('input[name="country"]').amsifySuggestags({
	suggestions: ['India', 'Pakistan', 'Nepal', 'UAE', 'Iran', 'Bangladesh'],
	whiteList: true,
	classes: ['bg-primary', 'bg-success', 'bg-danger', 'bg-warning', 'bg-info']
});

Each class will apply to each suggestion tag through their corresponding keys. We can also pass backgrounds and colors.

$('input[name="country"]').amsifySuggestags({
	suggestions: ['India', 'Pakistan', 'Nepal', 'UAE', 'Iran', 'Bangladesh'],
	whiteList: true,
	backgrounds: ['blue', 'green', 'red', 'orange', '#424242'],
	colors: ['white', 'black', 'white', 'black', 'white'],
});

We can also set class, color and background at each suggestion item if the suggestion items are object.

$('input[name="color"]').amsifySuggestags({
	suggestions: [
					{tag: 'Black', value: 1, background:'black', color:'white'},
					{tag: 'White', value: 2, background:'white', color:'black'},
					{tag: 'Red', value: 3, background:'red', color:'white'},
					{tag: 'Blue', value: 4, background:'blue', color:'white'},
					{tag: 'Green', value: 5, background:'green', color:'white'},
					{tag: 'Orange', value: 6, background:'orange', color:'white'}
				]
});

Same suggestions can also be passed in ajax response to get these stylings working

{
	"suggestions": [
		{
			"tag": "Black",
			"value": 1,
			"background":"black",
			"color":"white"
		},
		{
			"tag": "White",
			"value": 2,
			"background":"white",
			"color":"black"
		}
	]
}

Callbacks and Events

We can set callbacks on add/remove tag elements

$('input[name="country"]').amsifySuggestags({
	afterAdd : function(value) {
		console.info(value); // Parameter will be value
	},
	afterRemove : function(value) {
		console.info(value); // Parameter will be value
	},
});

or we can also subscribe to add/remove events

$('input[name="country"]').on('suggestags.add', function(e){
	// Do something after adding tag
});
$('input[name="country"]').on('suggestags.change', function(e){
	// Do something while add/remove tag
});
$('input[name="country"]').on('suggestags.remove', function(e){
	// Do something before removing tag
});

Tag Limit

We can also set tags limit

$('input[name="country"]').amsifySuggestags({
	tagLimit: 5
});

Refresh Destroy

For refreshing the values, you can use

var params = {
	// Make sure you have parameters which used during first execution
};
$('input[name="country"]').amsifySuggestags(params, 'refresh');

For destroying the instance, you can do

$('input[name="country"]').amsifySuggestags({}, 'destroy');

More Settings

selectOnHover

$('input[name="country"]').amsifySuggestags({
	selectOnHover: false
});

It will not select the suggested tag value when the mouse hover the suggestion item. By default the value is true

noSuggestionMsg

This will show message when there is no suggested item appears matching the input.

$('input[name="country"]').amsifySuggestags({
	noSuggestionMsg: 'Enter to generate new tag'
});

showAllSuggestions

This will show all the suggestion item on input focus. By default this is false

$('input[name="country"]').amsifySuggestags({
	showAllSuggestions: true
});

keepLastOnHoverTag

This will keep the last suggestion item in the input text field, even when moving away from the suggestion list. By default this is true. Useful when showAllSuggestions is set to true and you wish to hide the suggestion list when clicking away from the input text field.

$('input[name="country"]').amsifySuggestags({
	keepLastOnHoverTag: false
});

printValues

By default, input value and its tag names gets printed in console. You can set it false not to print in console.

$('input[name="country"]').amsifySuggestags({
	printValues: false
});

showPlusAfter

This setting is for hiding proceeding tags when focus is out of tags section and show the + number instead. By default it is 0, you can set the number to hide the tags after the given number when focus is out.

$('input[name="country"]').amsifySuggestags({
	showPlusAfter: 0
});

suggestMatch

A callback function can be passed to match the user entered text with suggestion item to show in suggestions list for custom matching.

$('input[name="country"]').amsifySuggestags({
	suggestions: ['India', 'Pakistan', 'Nepal', 'UAE', 'Iran', 'Bangladesh'],
	suggestMatch : function(suggestionItem, value) {
	    return ~suggestionItem.toString().toLowerCase().indexOf(value.toString().toLowerCase());
	}
});

This callback will receive two parameters, suggestion item value and the text value entered by user. Both parameters can be used to do custom matching and return non zero value to let that suggestion appear in suggestions list.

Instantiating

This is also one of the approach you can use this plugin.

Initilization

You can initialize by creating an instance of AmsifySuggestags and passing selector to it.

amsifySuggestags = new AmsifySuggestags($('input[name="country"]'));
amsifySuggestags._init();

Settings

You need to set it before initialization and you can use all the setting options shown in previous approach.

amsifySuggestags._settings({
	suggestions: ['Black', 'White', 'Red', 'Blue', 'Green', 'Orange']
})
amsifySuggestags._init();

Add/Remove Tag

You can call these methods to add/remove tag with instance of AmsifySuggestags

amsifySuggestags.addTag('Purple');
amsifySuggestags.removeTag('Red');

Refresh Destroy

You can call these methods to refresh/destroy

amsifySuggestags.refresh();
amsifySuggestags.destroy();

Note: This approach only works for single selector element not for multiple elements having same selector.
For making it work for selector having multiple elements, you can do something like this:

$('.tags-input').each(function(){
	amsifySuggestags = new AmsifySuggestags($(this));
	amsifySuggestags._init();
});
Comments
  • Autocomplete Interferes With Typing

    Autocomplete Interferes With Typing

    Hello. Great library.

    One thing we are finding while we use the library is that the autocomplete seems to interfere with typing out the tag manually. It seems like the resolution ought to be one or both of the below:

    1 - Typically, an autocomplete library will have a wait time from the last keystroke before autocomplete is attempted. I don't see in the library any mechanism for setting a timeout. 2 - When the autocomplete occurs, I've seen other libraries select the autocompleted text. That way, if the user keeps typing, their keystrokes overwrite and blow away the portion of the text that was autocompleted.

    Do either of these parameters exist in the library at all and I am just not seeing them defined anywhere? If they do not exist, is there a PR process you follow for merging suggestions into your main trunk? Are these changes that are compatible with your roadmap or should I fork the library for my unique usage?

    opened by dlernstrom 10
  • Ajax and back end code

    Ajax and back end code

    I am using c# to return this json from a database. The dropdown list is not triggering but the Json is returning

    ["adoptdontshop","America","Approvalratings","Atlanta","Based","Basedmemes","bitcoin", "blackcat","blackcatclub","blackcatlove","blackcatlover","blackcats","blackcatsmatter", "striketober","TheGreatResignation","TopNews","TPUSA","TPUSALive","transparency","trilliondollarbill", "uni","USA","VaccineNews","WhiteHouse","Winsomesears"]

    opened by TEStaff 8
  • mobile use

    mobile use

    hi! in mobile not working creating tabs, there is no enter key to activate the plugin by default the enter key changes to nexthttps://developerweb.cl/registro_chef.html WhatsApp Image 2020-04-27 at 12 09 03 PM please help !!!

    Originally posted by @eveperalta in https://github.com/amsify42/jquery.amsify.suggestags/issues/4#issuecomment-620083087

    opened by eveperalta 8
  • Doesn't works properly with russian keyboard layout

    Doesn't works properly with russian keyboard layout

    Russian letter "Б"(small "б") located on the same key as comma in english keyboard Can you set confirm key optional or verify e.key exactly match ',' symbol?

    opened by Romer4ig 6
  • Objects through Ajax

    Objects through Ajax

    Hello, how can I get suggestions as objects through Ajax ? I have a lot of repeated items in the suggestions list. This is the modified suggestions.php file

    <?php
    $suggestions 	= [['tag'=>'India','value'=>34], ['tag'=>'Pakistan','value'=>12], ['tag'=>'Nepal','value'=>43], ['tag'=>'UAE','value'=>11], ['tag'=>'Iran','value'=>21], ['tag'=>'Bangladesh','value'=>22],['tag'=>'Italy','value'=>23], ['tag'=>'Australia','value'=>134]];
    
    $data 			= [];
    
    foreach($suggestions as $suggestion)
    {
    	if(strpos(strtolower($suggestion['tag']), strtolower($_GET['term'])) !== false)	{
    		$data[] = $suggestion;	
    	}
    }
    
    header('Content-Type: application/json');
    echo json_encode(['suggestions' => $data]);
    
    opened by luizz 6
  • Why Post instead of Get for ajax suggestions?

    Why Post instead of Get for ajax suggestions?

    I just wonder why Post was preferred instead of Get for ajax call. I think it should be a simple get query with just a search term. Why do we have to send existing suggestions? I believe that the merging of suggestions should be done after the query locally.

    opened by codertimu 6
  • Ajax suggestions with relative path

    Ajax suggestions with relative path

    Hi everyone! Thanks for the great application!

    I would like to know how I can use a relative path to the ajax resource script. Currently I can only use the full URL. Is that possible?

    Thanks in advance

    opened by flaviorib-dev 5
  • Can we count tags in each row and show limit and show count.

    Can we count tags in each row and show limit and show count.

    I am trying to extend this library. I want here is to show tag count if tags more than 2. and rest I have to show remaining like for example.

    Total Tags 5. Display tags 2 and shows count +3

    Can we do that?

    image

    opened by hassanuos 5
  • Clicking Scroll Bar Closes Suggestions

    Clicking Scroll Bar Closes Suggestions

    We're observing an undesired behavior in the library where when we click on the scrollbar in order to scroll down to other tag suggestions, the focus changes in such a way as to close out the tag suggestions.

    For example: image

    When I put my mouse cursor on the scrollbar in order to scroll down to those suggestions that are lower, the focus on the form field is lost and the suggestion dropdown closes.

    Is this an easy fix? What are your thoughts?

    opened by dlernstrom 5
  • addTag don't eat objects

    addTag don't eat objects

    Method .addTag takes only VALUE that string, integer or other simple data.

    I tried to feed it with {tag: 'tagName', value: 666999} and it wont work. I fixed it with simple code, so there is purposed change:


    Old version of .getTag ():

    getTag : function(value) {
          if(this.settings.suggestions.length) {
            var tag = value;
            $.each(this.settings.suggestions, function(key, item){
              if(typeof item === 'object' && item.value == value) {
                tag = item.tag
                return false;
              }
              else if(item == value) {
                return false;
              }
            });
            return tag;
          }
          return value;
        },
    

    New version of .getTag ():

    getTag : function(value) {
          var returnValue = value; // buffer var for value
    
          if(this.settings.suggestions.length) {
            var tag = value;
            $.each(this.settings.suggestions, function(key, item){
              if(typeof item === 'object' && item.value == value) {
                tag = item.tag
                return false;
              }
              else if(item == value) {
                return false;
              }
            });
            return tag;
          }
          // it seems that object mode works only when some suggestions set in settings
          else if (typeof value === 'object' && value.tag) {
            returnValue = value.tag;
          }
          
          return returnValue; // return buffer var, with right tagName
        },
    

    Old version of .addTag():

        addTag : function(value) {
          if(!value) {
            return;
          }
          var html = '<span class="'+this.classes.tagItem.substring(1)+'" data-val="'+value+'">'+this.getTag(value)+' '+this.setIcon()+'</span>';
    
        ...
    

    New version of .addTag():

        addTag : function(value) {
          if(!value) {
            return;
          }
    
          // This temporary value need only to set data-val attribute below
          var temporaryValue = typeof value === 'object' && value.value ? value.value : value;
    
          var html = '<span class="'+this.classes.tagItem.substring(1)+'" data-val="'+temporaryValue+'">'+this.getTag(value)+' '+this.setIcon()+'</span>';
    
          // if value not exact  the same, then we need to re assign VALUE, we dont need to break code bellow
          if (temporaryValue !== value) {
            value = temporaryValue;
          }
    
        ...
    

    Hope it helps, maybe there is more cleanier way to solve issue, but i just hammer it down in simpliest and fastest way.

    Thank you for amaizing library o7

    opened by st-spark 5
  • Option to return values starting with input string

    Option to return values starting with input string

    Is there an option to only return results that start with the input letter string?

    We are sending an ajax request. Currently user inputs 'L'. Tags returned are:

    Filter1 Filter2

    What I would like is (only tags that start with an 'L'):

    Lambda List1

    opened by lharby 5
  • default  values without triggering afterAdd

    default values without triggering afterAdd

    Is there a way to trigger afterAdd only when a new tag is added, imagine initializing 100 tags and in afterAdd you have an ajax call to save it to db, all of them will fire at the same time

    opened by axwell 0
  • Get field extra data

    Get field extra data

    Hi,

    i have many tag fields in a table $('.tags').amsifySuggestags

    How i can get input data values in afterAdd function ? $(this).data('id') does not return anything

    Thanks

    opened by axwell 0
Owner
Amsify42
Amsify42
jQuery tags input plugin based on Twitter Bootstrap.

Bootstrap Tags Input Bootstrap Tags Input is a jQuery plugin providing a Twitter Bootstrap user interface for managing tags. Current stable version: v

null 26 Dec 21, 2022
Obsidian plugin that adds autocomplete and auto-formatting to frontmatter tags.

Obsidian Front Matter Tag Wizard Tired of having to type # to get tag autocompletion in your Obsidian note front matter? I feel your pain. This plugin

Eric 10 Nov 5, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
🔖 lightweight, efficient Tags input component in Vanilla JS / React / Angular / Vue

Tagify - tags input component Transforms an input field or a textarea into a Tags component, in an easy, customizable way, with great performance and

Yair Even Or 2.8k Jan 2, 2023
A Pure JavaScript Solution to create Tags Input Element.

JavaScript Tags Input Library Native JavaScript library to make Tags Input Element in DOM. There isn't any dependency for this library, add it straigh

Qamar ALi 11 Jun 27, 2022
Pure JS Auto Complete plugin with extra features.

Cndk.AutoComplete.js Cndk.AutoComplete.js is a pure JavaScript plugin. It performs auto-complete operations within an INPUT. Installation Include the

ILKERC 1 Jan 25, 2022
A Bootstrap plugin to create input spinner elements for number input

bootstrap-input-spinner A Bootstrap / jQuery plugin to create input spinner elements for number input. Demo page with examples Examples with floating-

Stefan Haack 220 Nov 7, 2022
Tag cloud plugin for jQuery, showing bigger tags in the center

jquery.tagcloud v1.2.0 Tag cloud plugin for jQuery, showing bigger tags in the center. Usage There are two ways to define a tag cloud: Use ul and li H

Peter Thoeny 1 Jun 30, 2022
Picky is a jQuery plugin that provides simple client-side date validation when entering dates using select tags.

jquery.picky.js Picky is a jQuery plugin that provides simple client-side date validation when entering dates using select tags. Features Instead of g

Patrick Crowley 5 Apr 25, 2021
A phone input component that uses intl-tel-input for Laravel Filament

Filament Phone Input This package provides a phone input component for Laravel Filament. It uses International Telephone Input to provide a dropdown o

Yusuf Kaya 24 Nov 29, 2022
Satyam Sharma 3 Jul 8, 2022
jquery-input-mask-phone-number.js - A simple, easy jquery format phone number mask library

jquery-input-mask-phone-number A jQuery Plugin to make masks on input field to US phone format. Quick start 1. Add latest jQuery and jquery-input-mask

Raja Rama Mohan Thavalam 12 Aug 25, 2022
infiniteScrollWithTemplate - JQuery plugin for ajax-enabled infinite page scroll / auto paging with template

jQuery Infinite With Template Plugin JQuery plugin for ajax-enabled infinite page scroll with template. If you like jQuery until now, this little libr

이삼구 2 Mar 19, 2021
Linkify is a JavaScript plugin for finding links in plain-text and converting them to HTML tags.

Linkify Linkify is a JavaScript plugin. Use Linkify to find links in plain-text and convert them to HTML <a> tags. It automatically highlights URLs, #

Hypercontext 1.5k Dec 27, 2022
A Jquery plugin that allows user to enter multiple emails using one input field

multi-emails A Jquery plugin that allows user to enter multiple emails using one input field Usage $("...").multiEmails() Options color textColor font

null 1 Aug 26, 2022
An easy-to-use jQuery plugin that allows the user to pick an icon from a responsive icon browser and shows the corresponding icon class in an input element.

Font Awesome Browser An easy-to-use jQuery plugin that allows the user to pick an icon from a responsive icon browser and shows the corresponding icon

Gianluca Chiarani 1 May 1, 2021