开发者

Help with jQuery text box length counter

开发者 https://www.devze.com 2023-01-25 20:20 出处:网络
I have a text box with a number outside of it that I initially set at 7 via script. When I type in the text box I want the number to decrease, when I delete characters I want it to increase. The scrip

I have a text box with a number outside of it that I initially set at 7 via script. When I type in the text box I want the number to decrease, when I delete characters I want it to increase. The script I have now decreases the number as expected, but when I delete it still decreases. When there is no characters left in the field and I press delete the number increases. Can someone put me on the right track? Thanks.

Here's what I have:

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_inse开发者_StackOverflow社区rt').html(origCnt);
    }
});            


The solution is actually a lot simpler:

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

Demo: http://jsfiddle.net/snpeX/


Why not just do this?

var origCnt = 7;

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

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

you can obviously add some tests to see if you go below zero and handle it in any fashion you need


It's Friday night and I didn't go out to start drinking yet so I wanted to do something to speed up the time even though the answer is already provided. I came up with this which will make it reusable and takes advantage of HTML features (in those rare times when there's no JavaScript).

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

0

精彩评论

暂无评论...
验证码 换一张
取 消