How to set default value in Tagify

1.4k Views Asked by At

I have an autocomplite input on my page, but i want to show some values before user begin typing I read Tagify documentation but find nothing about it I tried use tagTextProp but it not works When i set value attribute on my original input then autocomplite stop working

my input on the page

<div class="form-control">
              <input id="DetailsAddress" name="address" type="text" class="form-control__control" data-action="form-control" autocomplete="off">
              <div class="form-control__label"><?php EP_Lng::_e('Address'); ?></div>
            </div>
            <div class="form__alert form__alert_error" id="field_address" style="display:none;"></div>

my Tagify js code

  cityAutocomplete(input = null) {
    input = input || document.getElementById('city_autocomplete')
    let url = input.dataset.url || en4.core.baseUrl + 'pets/ajax/city';
    let whitelist = input.value ? JSON.parse(input.value) : [];

    let tagify = new Tagify(input, {
      enforceWhitelist: true,
      whitelist: whitelist,
      mode: 'select',
      value =[{"value":"bar"}],
      tagTextProp: 'value',
    });
    let controller;

    tagify.on('input', onInput)
    function onInput( e ) {
      var value = e.detail.value;
      tagify.settings.whitelist.length = 0; // reset the whitelist

      controller && controller.abort();
      controller = new AbortController();

      // show loading animation and hide the suggestions dropdown
      tagify.loading(true).dropdown.hide.call(tagify)

      let data = new FormData();
      data.append('text', value);
      fetch(url, {
        signal: controller.signal,
        method: 'POST',
        body: data
      })
      .then(response => response.json())
      .then(whitelist => {
        whitelist = whitelist.map(item => {
          return {
            value: item.label,
            id: item.id
          }
        })

        // update inwhitelist Array in-place
        tagify.settings.whitelist.splice(0, whitelist.length, ...whitelist)
        tagify.loading(false).dropdown.show.call(tagify, value); // render the suggestions dropdown
      })
    }

    tagify.on('change', onChange)
    function onChange(e) {
      // outputs a String
      let location_id = document.getElementById("location_id");
      if (!location_id) {
        console.warn('Hidden field location_id not found')
        return;
      }

      if (!e.detail.value) {
        location_id.value = '';
      } else {
        let value = JSON.parse(e.detail.value);
        location_id.value = value[0].id;
      }
    }

    return tagify
  }

How I use it

const addressInput = document.getElementById('DetailsAddress')
      this.cityAutocomplete(addressInput)
0

There are 0 best solutions below