jQuery文本输入长度控制 [英] jquery text input length control

查看:101
本文介绍了jQuery文本输入长度控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文本输入仅允许三个单词之间用空格隔开,如果超过3个,则用户将无法再输入,是否可以使用jQuery? 我可以使用keyup事件来侦听,但是如何阻止用户在不使用禁用的情况下输入更多令牌. 这有点类似于html中文本输入的本地maxlength属性,除了在这种情况下,maxLength是令牌数.

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.

推荐答案

检查输入是否已经包含3个单词,并且他们正在尝试输入空格.如果是这样,则返回false:

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

修改: 还有一个其他问题,该问题涉及有人可能会在字段中粘贴文本的情况.作为跨浏览器解决方案,我可能会将类似于@ karim79的代码绑定到blur事件.

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

这篇关于jQuery文本输入长度控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆