Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery text input length control

Tags:

jquery

the text input only allows three words separated by spaces, and if it exceeds 3, the user can't input anymore, is this possible using jQuery? I can use keyup event to listen, but how do I stop user from typing in more tokens without using disabled. This is sort of similar to the native maxlength property for the text input in html except that the maxLength in this case is the number of tokens.

like image 970
user121196 Avatar asked Dec 22 '22 10:12

user121196


1 Answers

Check if the input already has 3 words and they are trying to enter a space. If so return false:

$('#myTextbox').keydown(
    function(event)
    {
        var input = $(this).val();
        var numberOfWords = input.split(' ').length;
        if(numberOfWords == 3 && event.keyCode == 32)
        {
            return false;
        }
    }
);

Edit: There was an additional question about the situation where someone might past text in the field. As a cross browser solution I would probably bind code similar to @karim79's to the blur event.

$('#myTextbox').blur(
    function(e)
    {
        var tokens = $(this).val().split(' ');
        if(tokens.length > 3) 
        {
            $(this).val(tokens.slice(0,3).join(' '));
        }
    }
);
like image 169
Jataro Avatar answered Dec 24 '22 23:12

Jataro