treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Javascript text counter for textarea, off by one number!?

  • Howdy, so my text counter is off by one. How can i make the counter more accurate and be able to count when i hit the BACKSPACE button.

    Code:

    <!DOCTYPE html>
    <head>
    <title>help!?</title>
    <script type="text/javascript">
    function textCounter(field, countfield, maxlimit)
    {
    if (field.value.length > maxlimit)
    {
    field.value = field.value.substring(0, maxlimit);
    return false;
    }
    else
    {
    countfield.value = maxlimit - field.value.length;
    }
    }
    </script>
    </head>

    <body>
    <form>
    Comments:<br>
    <textarea rows="4" maxlength="300" onkeypress="textCounter(this,this.form.counter,300);">
    </textarea>
    <br>
    <input type="text" maxlength="3" name="counter" size="3" value="300" onblur="textCounter(this.form.counter,this,50);"readonly="readonly">
    words remaining.
    <br>
    <input type="reset" value="reset">
    </form>
    </body>
    </html>


    JS Fiddle Link:
    http://jsfiddle.net/john_motyl/y7qrs/1/

    Javascript / JQuery is not my strong suit so I really appreciate any feedback or advice. I watch my posts so any questions will be answered and comments will be replied to.

    Thank you.
  • @Maikel, thank you for that code. I see why it wasn't counting when i would backspace.

    Again, thanks.