帮助jQuery文本框长度计数器

时间:2010-11-19 23:56:25

标签: jquery

我有一个带有数字的文本框,我最初通过脚本设置为7。当我输入文本框时,我希望数字减少,当我删除字符时,我希望它增加。我现在的脚本按预期减少了数量,但是当我删除时它仍会减少。如果字段中没有剩余字符,我按删除数字会增加。有人能让我走上正轨吗?感谢。

这就是我所拥有的:

var origCnt = 7;

$('#cntEngDesg_insert').html(origCnt);

$('#txtEngDesg_insert').keyup(function () {
    var currentlen = $('#txtEngDesg_insert').val().length;
    if (currentlen++) {
        origCnt--;
        $('#cntEngDesg_insert').html(origCnt);
    }
    else if (currentlen--) {
        origCnt++;
        $('#cntEngDesg_insert').html(origCnt);
    }
});            

3 个答案:

答案 0 :(得分:4)

解决方案实际上要简单得多:

var origCnt = 7;

$('#cntEngDesg_insert').html(origCnt);

$('#txtEngDesg_insert').keyup(function (e) {
    var currentlen = $('#txtEngDesg_insert').val().length;
    if(currentlen <= origCnt) {
        $('#cntEngDesg_insert').html(origCnt - currentlen);
    } else {
        $(this).val($(this).val().substring(0, origCnt));
    }
});  

演示:http://jsfiddle.net/snpeX/

答案 1 :(得分:0)

为什么不这样做?

var origCnt = 7;

$('#cntEngDesg_insert').html(origCnt);

$('#txtEngDesg_insert').keyup(function () {
    var currentlen = $('#txtEngDesg_insert').val().length;
    $('#cntEngDesg_insert').html(origCnt - currentlen );
});       

你显然可以添加一些测试,看看你是否低于零,并以任何你需要的方式处理它

答案 2 :(得分:0)

这是星期五晚上,我还没有出去喝酒,所以我想做点什么来加快时间,即使答案已经提供了。我想出了这个可以重用它并利用HTML功能(在没有JavaScript的极少数情况下)。

http://pastie.org/pastes/1312188/text

相关问题