Stefan
Stefan

Reputation: 322

jquery autocomplete special char trigger

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");
    }

});

Upvotes: 3

Views: 5139

Answers (2)

j809
j809

Reputation: 1499

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.

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

$(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;
      }
    });
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>

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

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 behavior working: http://jsfiddle.net/rPfY8/1/

$(function() {
  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);
          if(lastword[0] != '@')
              return false;
          // Get all labels
          var labels = utilizatoriJson.map(function(item){return item.label;});
          response( $.ui.autocomplete.filter(
          labels, 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;
      }
    });
});
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>

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

Upvotes: 9

caspian
caspian

Reputation: 1804

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;
        }
    });
});

Upvotes: 0

Related Questions