yuku / textcomplete

Autocomplete for HTMLTextAreaElement and more.

Home Page:https://yuku.takahashi.coffee/textcomplete/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problem to show suggestions based on condition

shivrajsa opened this issue · comments

Based on some condition I want to display different suggestions, please refer below code, where if condition is 0 I want to use obj1 else if it is 1 then I want to use obj2.

But below code is not working as expected, every time I get suggestions from only one object which was selected first time as per condition. Please help to solve the problem

function autoComplete(condition) {
  var obj1 = {
      A: 'a',
      B: 'b'
    },
    obj2 = {
      A: 'X',
      B: 'Y'
    },
    words = ['A', 'B'];

  $('.handsontableInput').textcomplete([{
      match: /(^|\b)(\w{0,})$/,
      search: function(term, callback) {
        callback($.map(words, function(word) {
          return word.indexOf(term) === 0 ? word : null;
        }));
      },
      template: function(word) {
        var x;
        if (condition == 0)
          x = word + '&nbsp&nbsp' + '<span class="NotationsAutoComplete">' + obj1[word] + '</span>';
        else if (condition == 1)
          x = word + '&nbsp&nbsp' + '<span class="NotationsAutoComplete">' + obj2[word] + '</span>';
        return x;
      },
      replace: function(word) {
        return word + ' ';
      }
    }

I get suggestions from only one object which was selected first time as per condition

It is because the condition argument is in closure. In other words, the condition is fixed when you execute the autoComplete function and never change.

You can fix the problem by moving the condition from function argument to outer variable.

var condition;

function autoComplete() {
  ...
  $('..').textcomplete([{
    template: function (word) {
      if (condition) {
        return word + '...';
      } else {
        ...
      }
    }
  }])
}

Thank you, its working now :-)