In jQuery, how to determine the specified string when the user prints it?

As with entering a comment on Facebook, and you click on @username, it responds to this by letting you choose an inline username.

Using jQuery, how could I hook up an event listener for [text: 1]. I want the event to fire when the user types [text: in a text box.

+4
source share
3 answers

use the keyup function to run. Separate the entire line and check it.

[UPDATE]: 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" /> 
+2
source

Zurb has created a text messaging plugin that will help. See the “Validate Text” example below, I think this is almost what you are looking for.

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

+4
source

Using keyup , as mentioned in @experimentX's description, is how you want to go b / c, then you will know that your user has the entered value. However, executing a for loop will be extremely expensive in every keyup event. Instead, since you already know the value you need, you can use the regexp preset 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 some additional scenarios on how you can write the actual regexp .

  • You want the line to be at the very beginning of the input: var regexp = /^\[text\:/i;
  • Based on the above, but add any number of spaces before the text that you really want: var regexp = /^\s+?\[text\:/i;
+1
source

Source: https://habr.com/ru/post/1342575/


All Articles