Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

});
like image 538
Stefan Avatar asked Jun 03 '26 18:06

Stefan


1 Answers

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>
like image 159
j809 Avatar answered Jun 05 '26 12:06

j809



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!