How to delete tags in Tagify plugin?

4.8k Views Asked by At

I need to handle a dynamic button that will remove all the Tagify tags. The documentation for deleting all tags with jQuery is here: https://yaireo.github.io/tagify/#section-jquery

In the documentation it says:

// get the Tagify instance assigned for this jQuery input object so its methods could be accessed
var jqTagify = $input.data('tagify');

// bind the "click" event on the "remove all tags" button
$('.tags-jquery--removeAllBtn').on('click', jqTagify.removeAllTags.bind(jqTagify))

With this in mind, I have tried without success the following (can be seen here in JSFiddle):

$(document).on('click', '#btn-test', function()
{
    var $input = $('#input-test').tagify();    
    $input.removeAllTags();
});

I also tried to create an approach closer to what the documentation states:

$(document).on('click', '#btn-test', function()
{
    var $input = $('#input-test');
    var _tagify = $input.data('tagify');

   _tagify.removeAllTags();
});

But in both situations the error is:

Cannot read property 'removeAllTags' of undefined

I can't bind directly the remove function to a DOM element because buttons will be created on-the-fly.

3

There are 3 best solutions below

0
On

It works for me this way

 var prueba = '"Lic","ffff","asdasd","asdd","asd","dsdsd"';
 var $input = $('input[name=tags]');
 var jqTagify = $input.data('tagify');
 jqTagify.addTags(prueba);
 jqTagify.removeAllTags();
0
On

$input.data('tagify') will not work and will return undefined because you did not initialize Tagify using jQuery per the instructions in the docs:

$('#input-test').tagify()

The above is how all jQuery plugins are used when applied to a DOM node - you first instantiate a jQuery object and then apply the jQuery plugin on it. Once you do it like that, the data property tagify will be available: $input.data('tagify')

Instead, you initialized it like the vanilla version, using new Tagify(...).

0
On

in jquery:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tagify/3.16.3/tagify.min.css" />
<input name='tags-jquery' id="input-test" >
<button id="btn-test">
  Delete
</button>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tagify/3.16.3/jQuery.tagify.min.js"></script>

<script>
var $el = $('#input-test').tagify()
var jqTagify = $el.data('tagify')
var btn = $('#btn-test')
btn.on('click', jqTagify.removeAllTags.bind(jqTagify))
</script>