I have a Text Field that only allows 20 characters, and I want to display a countdown message as the user enters values in the field. I have it working based on the following approach but was wondering if there was a more elegant solution?

My Text Field (i.d. demo3) has the following code in a Focus Rule

var maxLength = 20;
$('#demo3').keyup(function() {
var fldLength = $(this).val().length;
fldLength = maxLength-fldLength;

In my Text Display, I edit the source to include an id (chars) so that the reference works in the above script :

Maximum of <strong>20</strong> characters allowed. You have <strong><span id="chars">20</span></strong> characters left to describe your complaint.

While this seems to work fine, I was just wondering if there was another way of approaching this?


    CommentAdd your comment...

    1 answer


      Hi Gary,

      I'd be more inclined to do it slightly differently... in a Form Load rule:

        $(document).on('keyup', '#demo3', function (event) {
          var maxLength = $(event.target)[0].maxLength;
          var fldLength = $(event.target)[0].value.length;
          $('.id-chars').text((maxLength-fldLength) + ' characters remaining');

      There's a couple of advantages:

      1. picking up the max length dynamically means you could apply the same hook to multiple targets
      2. The delegated form of the jQuery .on method means that any future-added elements will inherit that hook
      3. Focus happens more often than form Load
      4. Using the event.target as a jQuery selector makes it more generic
      5. Using .id-chars as a selector means you don't need to edit the text display source
        CommentAdd your comment...