adbdude
adbdude

Reputation: 3

jQuery Counter Not Working

JavaScript/jQuery newbie here!

I have the following form here (using bootstrap's disabled class, heads up):

EDIT: the class 'disabled' is a thing in bootstrap, and does properly disable and enable the button if it is there or not.

<form action="" method="post">
<input type="text" id="bio">
<p class="bio-counter"></p>
<input type="text" id="username">
<p class="user-counter"></p>
<input type="submit" class="btn">
</form>

And the following script (I have included jQuery in my head tag correctly):

var main = function() {
   $('.bio-counter').text('500');
   $('.user-counter').text('0');
   var postLengthUser = $('#username').val().length;
   var postLengthBio = $('#bio').val().length;
   $('#username').keyup(function() {
     $('.user-counter').text(postLengthUser);
   });
   $('#bio').keyup(function() {
    var charactersLeftBio = 500 - postLengthBio;
    $('.bio-counter').text(charactersLeftBio);
  });
  if(postLengthUser > 6 && postLengthUser < 21) {
    if(postLengthBio >= 0 && postLengthBio < 501) {
      $('.btn').removeClass('disabled');
    } else {
      $('.btn').addClass('disabled');
    }
  } else {
    $('.btn').addClass('disabled');
  }
}

$(document).ready(main);

I am running into the following problems:

What am I doing wrong?

Upvotes: 0

Views: 1003

Answers (2)

Jacek Zyśk
Jacek Zyśk

Reputation: 134

<script>
    var main = function () {
        var postLengthUser = 0;
        var postLengthBio = 0;

        $('.bio-counter').text(500);
        $('.user-counter').text(0);


        var validate = function () {
            if (postLengthUser > 6 && postLengthUser < 21) {
                if (postLengthBio >= 0 && postLengthBio < 501) {
                    $('.btn').removeClass('disabled');
                } else {
                    $('.btn').addClass('disabled');
                }
            } else {
                $('.btn').addClass('disabled');
            }
        }

        $('#username').keyup(function () {
            postLengthUser = $('#username').val().length;
            $('.user-counter').text(postLengthUser);

            validate();
        });

        $('#bio').keyup(function () {
            postLengthBio = $('#bio').val().length;
            var charactersLeftBio = 500 - postLengthBio;
            $('.bio-counter').text(charactersLeftBio);

            validate();
        });

        validate();
    }

    $(document).ready(main);
</script>
  1. You're validating the disabled condition only at page load, it should be run at each keyup event - i moved it to validate function.

  2. postLengthUser and postLengthBio were updated only at page load too. They should be updated on each key up event too.

Upvotes: 2

J. Titus
J. Titus

Reputation: 9690

Try using:

$('.btn').prop('disabled', true);

and

$('.btn').prop('disabled', false);

instead.

Upvotes: 1

Related Questions