开发者

In jQuery, how to detect specified string while user is typing it?

Much like when typing a comment on Facebook and you hit @username, it re开发者_如何学运维acts to that, letting you choose a username inline.

Using jQuery, how would one go about hooking up an event listener for [text:1]. I want an event to fire when the user has entered [text: into a text field.


Zurb created a textchange plugin that will help. See their "Validate Text" example towards the bottom, i believe its almost exactly what you're looking for..

http://www.zurb.com/playground/jquery-text-change-custom-event


use keyup function to trigger. Split all the string and check it.

[UPDATE]: More Improved Version

<script>

var totalcount=0;

$(function (){

    $('#text').keyup(

        function (){

              var arr = $(this).val().split(" ");

              var matchitems = count('hello', arr);

              //console.log(matchitems);

              if(matchitems > totalcount){
                alert('hello');
                totalcount = matchitems;
              }
              if(matchitems < totalcount)
              {
                totalcount = matchitems;
              }

        }
    )

})

function count(value, array)
{
    var j=0;

    for(var i=0;i<array.length;i++)
    {

        if(array[i] == "hello"){
            j++;    
        }
    }
    return j;
}

</script>

<input type="text" id="text" />
})

</script>

<input type="text" id="text" />


Using keyup like @experimentX mentioned is the way you want to go b/c then you'll know that your user has inputed value then. However, running a for loop would be extremely costly on every single keyup event. Instead, since you know the value you want already, you can use a preset regexp to search for your value:

<input type="text" id="text" value="" />

<script>
    $(function () {
        var $input = $('#text');
        $input.keyup(function (e) {
            var regexp = /\[text\:/i,
                val = $(this).val();
            if (regexp.test(val)) {
                console.log('i have it: ', val);
            }
        });
    });
</script>

Here are a couple additional scenarios on how you can write the actual regexp.

  • You want the string to be at the very beginning of the input: var regexp = /^\[text\:/i;
  • Building on the one above, but incorporate any amount of whitespace in front of the text you actually want: var regexp = /^\s+?\[text\:/i;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜