The Tagify dropdown with suggestions works in JS but not in jQuery

1.5k Views Asked by At

I am using Tagify to allow the user to indicate or select tags for the publication of an article.

In addition to typing in tags, I need to list some suggestions that are already in the database. At the moment I have not used Ajax because I am doing some tests to see how it should actually work. Nevertheless, the same plug-in works in JS but not in jQuery. The code snippet for opening the dropdown does not work in jQuery.

Where am I going wrong?

JS

var tagify = new Tagify(document.getElementById('app-tag-input'), {whitelist: []});
tagify.on('input', onInput);

function onInput(e) {

   var value = e.detail.value;
   tagify.whitelist = null;
   tagify.loading(true).dropdown.hide(); 
   tagify.whitelist = [{id: 1, value: 'html'}, {id: 2, value: 'css'}];
   tagify.loading(false).dropdown.show(value);

}

jQuery

var tagify = $('input[name="tag"]').tagify({whitelist: []});

tagify.on('input', onInput);

function onInput(e, tagName) {

   var value = tagName.value;
   tagify.whitelist = null;
   tagify.data('tagify').loading(true).dropdown.hide();
   tagify.whitelist = [{id: 1, value: 'html'}, {id: 2, value: 'css'}];
   tagify.data('tagify').loading(false).dropdown.show(value);

}

HTML

<input type="text" name="tag" id="app-tag-input">
1

There are 1 best solutions below

1
On

In the jquery version, to access tagify properties you need to use:

tagify.data('tagify').

this also applies to the tagify.whitelist = call:

tagify.data('tagify').whitelist = 

which was missing from the jquery version.

Updated fiddle: https://jsfiddle.net/xoap1knt/

Updated code: Unfortunately, a snippet doesn't work in SO as it appears tagify uses localStorage for some unknown reason.

$(function () {
  var tagify = $('input[name="tag"]').tagify({whitelist: []});
  tagify.on('input', onInput);
  function onInput(e, tagName) {
    var value = tagName.value;
    tagify.whitelist = null;
    tagify.data('tagify').loading(true).dropdown.hide();
    tagify.data('tagify').whitelist = [{id: 1, value: 'html'}, {id: 2, value: 'css'}];
    tagify.data('tagify').loading(false).dropdown.show(value);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/tagify/4.16.4/jQuery.tagify.min.js'></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/tagify/4.16.4/tagify.min.css" />
<form action="save.php">
  <fieldset>
    <input type="text" name="tag">
  </fieldset>
</form>