Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a HTML input field, lets say

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

I need to trigger a function on every 3 charachters entered.

For example:

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

But spaces should not be counted.

I need this to post value of the field to external API - to do searching.

Has anybody done this before?

Please help.

like image 798
Kirill Reva Avatar asked Feb 11 '13 12:02

Kirill Reva


2 Answers

try something like this. Bind an event handler to input on page load

$(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
         }

    });      
});
like image 60
Hary Avatar answered Nov 15 '22 06:11

Hary


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

$('#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

like image 25
Ruben Infante Avatar answered Nov 15 '22 07:11

Ruben Infante