jquery text input length control

后端 未结 3 1119
情深已故
情深已故 2021-01-06 05:48

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 liste

3条回答
  •  庸人自扰
    2021-01-06 06:42

    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(' '));
            }
        }
    );
    

提交回复
热议问题