开发者

JS/jQuery : Best way to get typed characters after '#' in textarea

I am creating a smart textarea that needs to recognise a term typed after the '#' symbol.This needs to be able to work for the term CURRENTLY being typed and be able to work for multiple instances of the '#' symbol in a single textarea.

It is designed to work the same way as Facebook when you type 开发者_开发问答the '@' symbol to tag a person in a post. A drop down list will appear and list items will get filtered depending on the term after the '#' symbol.

This also needs to work if the user were to type a term then amend it later. I understand this complicates things a little.

What is the best way to achieve this functionality?


I don't know if it helps but here's i small script to find the hashes.
http://jsfiddle.net/aNgVV/


I suggest you look at the jQuery UI demo for the Autocomplete widget, specifically the demo for using a remote datasource with cache. Specifically for the following reasons:

  1. It automatically takes care of the drop-down widget you mentioned.
  2. It demonstrates how you can populate that drop-down with items based on an AJAX call (which I presume you need).
  3. The demo for Autocomplete caching parses the text in the INPUT element, as it tries to determine whether or not the value the user is currently typing has already been cached, and reacts accordingly. I assume you can do something similar to check for the # types, and to check if a previous # tag is being modified as well.


Initially you need to catch the '#' key being pressed and then capture the subsequent key presses and pass them to a function to handle your auto completion requirements. A rough outline to of the code is below. You may need to catch whitespace key presses as well to stop the auto-completion.

var hashKeyPressed = false;

$('#TextArea').keyup(function(event) {
    if(event.keyCode == '222') {
        // this will catch the '#' key
        hashKeyPressed = true;
    }
    if(hashKeyPressed) {
        // Here you can start build up subsequent key presses into a string
        // and pass them to a function to handle the auto-completion
    }
}); 


You can capture the keyup event and check what has been entered last like so:

       $('#myTextArea').keyup(function () {

            var len = $(this).val().length;

            if ($(this).val().substring(length - 1, 1) == '#') {

                // Do whatever you want to do here

            }

        });

EDIT:

You are right - you could do it this way instead:

$('#myTextArea').keypress(function (e) {

    if (e.which == 222) {

        // do something here

    }

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜