2

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_insert').html(origCnt); } }); 

3 Answers 3

4

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/

Sign up to request clarification or add additional context in comments.

2 Comments

should have refreshed before submitting my identical solution :)
@nick - I just edited it, now it will actually restrict input to the correct length, plus there is a demo. @Variant - I do that all the time :)
0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.