Home > OS >  Convert text to tag in Tagify
Convert text to tag in Tagify

Time:10-22

I would like to know how it is possible by code to convert a text to a tag. Suppose we have the following text:

[[{"value":2,"text":"Petrol Man","title":"Petrol Man","prefix":"@"}]]

how do I, via code convert it to the tagify classic graphical display?

EDIT:

I would convert this text [[{"value":2,"text":"Petrol Man","title":"Petrol Man","prefix":"@"}]] to:

enter image description here

CodePudding user response:

With the assumptions:

tagify v4.12.0 from https://github.com/yairEO/tagify

provided data is a JSON string containing a nested array [[{..}]]

The tagify page has an example of adding new tags:

tagify.addTags(["banana", "orange", "apple"])

so you need to convert your json-string to an array of text values.

Use JSON.parse to convert to an object then data[0].map( to read each value out of the inner array - as the outer array (in the sample at least) is always a single dimension, you need data[0] to get to the inner array.

Put together:

var tagify = new Tagify(document.getElementById("tags"));

//tagify.addTags(["banana", "orange", "apple"])

// added a second example in the inner array otherwise it's just `data[0][0].title`
var txt = '[[{"value":2,"text":"Petrol Man","title":"Petrol Man","prefix":"@"}, {"text":"Diesel Woman"}]]';
var data = JSON.parse(txt);
var newTags = data[0].map(t => t.text);

tagify.addTags(newTags);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify"></script>
<script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.polyfills.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet" type="text/css" />

<input id='tags'>

Unfortunately, the plugin uses localStorage without checking if it's available - and SO doesn't allow this, so no working snippet above, but here's a working fiddle: https://jsfiddle.net/50n7ckLe/

  • Related