How can I implement tag selection that prevents arbitrary tags from being written?

I need to implement a tag or category selector on an HTML page.

Tags must be provided to the user and they are not allowed to enter an arbitrary tag.

jQuery UI provides a very popular automatic full implementation , but it seems to let you select arbitrary tags.

In the screenshot below, I am allowed to select "j" and "javascript" without much effort.

Are there any methods, implementations or third-party tools that I can use for that do not allow the user to enter arbitrary tags?

Edit: my web application works using PHP, jQuery, jQuery-UI, MySQL and common front-end tools.

enter image description here

+4
source share
1 answer

If using an additional library is not a problem for you, Bootstrap solves your problem with a little jQuery help.

I have prepared a simple JSFiddle for you, where you can see it in action:

http://jsfiddle.net/sgmonda/Tjbys/8/

What I did was prepare text input and a <ul> list where your selected tags will be displayed. Bootstrap allows autocomplete when writing to the input, so you should disable autocomplete by default:

 <input type="text" id="tags" autocomplete="off" /> <ul id="selected-tags"></ul> 

Then you just need to add some jQuery lines so that Bootstrap will autocomplete your input and add the selected tags to your <ul> list:

 $('#tags').typeahead({ source: ['elem1', 'elem2', 'elem3', 'otherElem', 'oneMore'], updater: function (item) { $('#selected-tags').append('<li>' + item + '</li>'); } }); 

Whenever you want, you can read the list to find out which items have been selected by the user.

 var selectedTags = []; $('#selected-tags').each(function(){ selectedTags.push($(this).text()); }); 

EDIT

If you want to avoid duplication of tags and add the ability to remove them:

http://jsfiddle.net/sgmonda/JMepQ/3/

+3
source

All Articles