jquery autocomplete special char trigger

五迷三道 提交于 2019-12-05 06:12:15

问题


i have the following problem:

i must make a special autocomplete with jquery triggered by char "@"

the problem is that if i begin the textbox with @ it works but if i enter @ after i write some chars it doesn't work.

how it must work: -i write some text an i want to add someone from "utilizatoriJson", -to add someone from "utilizatoriJson" i must press the @ key and an autocomplete dropdown must apear, -after i select someone from dropdown or i type a full label from dropdown it must put space and let me continue my message

how can i do this ?

code that i wrote :

var utilizatoriJson = <%=utilizatoriJson%>;

$( '#textarea_mesaj_colaborare').autocomplete({
    source: utilizatoriJson

})            .autocomplete( "instance" )._renderItem = function( ul, item ) {
    return $( "<li>" )
            .append( "<a>" + item.label + "</a>" )
            .appendTo( ul );
}
$( '#textarea_mesaj_colaborare').autocomplete("disable");


$('#textarea_mesaj_colaborare').keyup(function(){
    if ($('#textarea_mesaj_colaborare').val()[$('#textarea_mesaj_colaborare').val().length-1]==='@'){
        var inceput = $('#textarea_mesaj_colaborare').val().length;

        $( '#textarea_mesaj_colaborare').autocomplete("enable");
    }

});

回答1:


As already mentioned, you would require multiple words approach here.

The link to original source has already been provided above. So, I would like show what I understood from your doubt.

But first let me know if you want to have autocompletion like after '@' all label that start with 'a' should give results that only start with 'a' and not those which contain 'a'.

Since I suppose this would be of much better use, I have code for that part.

Your HTML

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags" size="50">
</div>

Your JS

$(function() {
    //Since you told that labels start with '@'
    var utilizatoriJson = [
        {'label': "@ActionScript",'id':'1'},
        {'label': "@Java",'id':'2'},
        {'label': "@C++",'id':'3'},
        {'label': "@Javascript",'id':'4'},
        {'label': "@Python",'id':'5'},
        {'label': "@BASIC",'id':'6'},
        {'label': "@ColdFusion",'id':'7'},
        {'label': "@Haskell",'id':'8'},
        {'label': "@Lisp",'id':'9'},
        {'label': "@Scala",'id':'10'}
    ];
    function split( val ) {
      return val.split( / \s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 1,
        source: function( request, response ) {
            // delegate back to autocomplete, but extract the last term
            var lastword = extractLast(request.term);
            // Regexp for filtering those labels that start with '@'
            var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( lastword ), "i" );
            // Get all labels
            var labels = utilizatoriJson.map(function(item){return item.label;});
            var results = $.grep(labels ,function( item ){
                             return matcher.test( item );
                        });
            response( $.ui.autocomplete.filter(
            results, lastword ) );
        },
        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;
        }
      });
  });

Working Demo : http://jsfiddle.net/AJmJt/2/

If you don't want something like I said, then there is no need for RegExp matching, but there you need to see if word starts with '@' or not.

Code for this behaviour working : http://jsfiddle.net/rPfY8/1/




回答2:


You don't want to disable/re-enable the autocomplete as that prevents the control from doing anything. You can do this the way you propose, but there's another approach. Take a look at the example here: http://jqueryui.com/autocomplete/#multiple

This should do what you're looking for, you can update the filter to only do a "starts with" search

Here's a JSFIDDLE example of what I mean: http://jsfiddle.net/UhL5d/

And the corresponding Javascript:

$(function () {
    var availableTags = [
        {value: 1, label: "@ActionScript" },
        {value: 2, label: "@AppleScript" },
        {value: 3, label: "@Asp" },
        {value: 4, label: "@BASIC" },
        {value: 5, label: "@C" } ];

    function split(val) {
        return val.split(/\s/);
    }

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

    $("#textarea_mesaj_colaborare").autocomplete({
        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.label);
            // add placeholder to get the comma-and-space at the end
            terms.push("");
            this.value = terms.join(" ");
            return false;
        }
    });
});


来源:https://stackoverflow.com/questions/24533562/jquery-autocomplete-special-char-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!