Activation of actions after the third charecter

Hi, can someone help me figure out how to stop a function from being executed until a certain number of characters are pressed?

currently using the following function:

$('input#q').keyup 

it works as soon as you press any key ...

+4
source share
5 answers

Something like this should start with an activation code after adding 3 letters:

Live example

Javascript

 $('input#q').keyup( function() { if( this.value.length < 4 ) return; /* code to run below */ $('#output').val(this.value); }); 

HTML

 <input id="q" /> <br /><br /> <input id="output"/> 
+11
source

You can store characters in a string variable each time you press a key, and then run a conditional statement to check the length of the variable. If it is three, execute any function

+2
source

You can do:

 $('input#q').keyup(function(){ if($(this).val().length > 3) { //do something } }); 
+1
source

Well, you probably need to consider ways to change focus. Do you want to clear the counter when the field is again focused or not? You must also decide whether you are actually counting the characters in the field, or if you want the actual discrete keystrokes — pressing the shift key, for example, will not add any characters, but that key is pressed.

In any case, perhaps it will be something like this:

 $(function() { var keyCount = 0; $('#q').keyup(function() { // "keypress" to count characters if (++keyCount === 3) { // do the thing } }) .focus(function() { keyCount = 0; // if this is what you want }); }); 

If you consider the event "keypress" instead of "keyup", you may need to calculate the actual length of the text field value, rather than trying to count the events.

0
source

What about:

 var c = 0; ('input#q').keyup( function() { c++; if (c >= 3) { startGame(); } } ); 
0
source

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


All Articles