Trigger event with jquery when 3 characters are entered in the input field

I have an HTML input box, say

<input type="text" maxlength="50" size="50" name="subject" id="subject"> 

I need to call a function for each character entered.

For instance:

If the user enters "aaa" - triggers the event, he continues to enter "aaa bbb" - the trigger event again, etc.

But gaps should not be considered.

I need this to publish the field value for an external API - for search.

Has anyone done this before?

Please, help.

+4
source share
2 answers

try something like that. Bind an event handler to input when loading a page

 $(function(){ $("#subject").change(function(){ var val = $(this).val().trim(); val = val.replace(/\s+/g, ''); if(val.length % 3 == 0) { //for checking 3 characters //your logic here } }); }); 
+8
source

If you want to actually do this in real time while the user is typing and does not require them to remove the focus from the input, you can use the keyup event and slightly modified logic to filter out white space clicks.

 $('#subject').on('keyup', function(e) { if (e.which !== 32) { var value = $(this).val(); var noWhitespaceValue = value.replace(/\s+/g, ''); var noWhitespaceCount = noWhitespaceValue.length; if (noWhitespaceCount % 3 === 0) { // Call API } } }); 

jsfiddle

+8
source

All Articles