Search code examples
jqueryindexofkeyup

alert after typing @ plus one more letter Jquery


I am creating a textarea to create posts, where if I type @ plus one more letter, then it appears an alert () the one which will be replaced by an inline user search bar like twitter (I already have it).

  <textarea id=post></textarea>

       $(function() {
         $('#post').keyup(function() {
             if ( $(this).val().indexOf("@") > -1 ) {
                 alert("found");
              }
            });
      });

I'm using this function, it recognizes the @ but if continue writing something else, the alert continues showing up. What I want is the alert appears after writing @ and another letter to make the inline search bar works.


Solution

  • I made a Snippet for you.

    This uses "count" to check if the amount of characters in the textarea changes. Because the "@" can be made using "AltGr+2" (2 keyups) or "Alt+64" (3 keyups). The code belows avoid problems with ASCII characters that can be formed that way.

    Also, I checked from "lastChar" instead your indexOf("@"). This allows you to fire your tag function more than once in the same textarea.

    Like "Hey @Jean, I'm @NiMusco and hope it helps you".

    Sure it can be improved, but by way of example it's fine.

    var count = 0;
    var tagging = false;
    var users_example = ["jean", "nimusco"];
    
    $('#post').keyup(function(){
      var text = $(this).val();
      
      if(text.length > count){
        var lastChar = text.substr(count);
        
        if(lastChar == "@"){
          tagging = true;
        }
        
        //White space break the tagging.
        if(lastChar == " "){
          tagging = false;
        }
        
        //Adapt this to your tagging function
        if(tagging == true){
          var username = text.substr(text.lastIndexOf('@') + 1, text.length);
          console.log(username);
          if($.inArray(username.toLowerCase(), users_example) !== -1){
            alert('found it!');
            tagging = false;
          }
        }
      }
      
      count = text.length;
    });
    #post{
    width:300px;
    height:150px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <textarea id="post">
    
    </textarea>