当我使用jquery-ui自动完成功能在文本区域键入内容时,如何在任何位置实现自动完成功能?

时间:2019-05-08 06:14:00

标签: jquery html razor

我想在文本区域的任何位置自动完成主题标签,例如当我键入“ #rain #nature的照片”时,我想在有人使用jquery自动完成功能键入以“#”开头的任何内容时显示建议。

<textarea class="form-control" rows="3" id="comment"></textarea>

我的数据库中存储了#标签。

$('#comment').keyup(function (e) {
    var key = String.fromCharCode(e.which);
    console.log(key);
    if (key == 3) {
        //debugger;
        $('#comment').autocomplete({
            delay: 100,
            source: function (request, response) {
                var url = '@Url.Action("GetHashtags", "Common")';
                $.post(url, { str: request.term }, function (data) {
                    console.log(data);
                    response($.map(data, function (item) {
                        return { value: item.HashtagName };
                    }));
                });
            }
        });
    }
});

它在句子开头很好用,但是在输入单词后不起作用。

1 个答案:

答案 0 :(得分:0)

找到解决我问题的方法。这是示例-

https://jsfiddle.net/atiqbaqi/rsmq07Lu/3/

<div class="ui-widget">
  <label for="tags">Tag programming languages: </label>
  <textarea id="tags" size="50"></textarea>
</div>

jquery:

$(function() {
  var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
  ];

function split(val) {
return val.split(/ +/);
  }

function extractLast(term) {
return split(term).pop();
  }

  $("#tags")
// don't navigate away from the field on tab when selecting an item
.on("keydown", function(event) {
  if (event.keyCode === $.ui.keyCode.TAB &&
    $(this).autocomplete("instance").menu.active) {
    event.preventDefault();
  }
})
.autocomplete({
  minLength: 3,
  source: function(request, response) {
    // delegate back to autocomplete, but extract the last term
    response($.ui.autocomplete.filter(
      availableTags, extractLast(request.term)));
  },
  focus: function() {
    // prevent value inserted on focus
    return false;
  },
  select: function(event, ui) {
    var terms = split(this.value);
    // remove the current input
    terms.pop();
    // add the selected item
    terms.push(ui.item.value);
    // add placeholder to get the comma-and-space at the end
    terms.push("");
    this.value = terms.join(" ");
    return false;
  }
});
});