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

时光毁灭记忆、已成空白 提交于 2019-12-10 13:46:08

问题


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.


回答1:


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
         }

    });      
});



回答2:


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



来源:https://stackoverflow.com/questions/14812267/trigger-event-with-jquery-when-3-characters-are-entered-in-the-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!