Search code examples
jqueryruby-on-railsformsslim-lang

jQuery character count onkeyup showing 1 character when 0 left


I'm using jQuery to show characters remaining in a text input and it's working fine but when it gets to 0 characters remaining it is showing 1 even though it doesn't allow you to enter more. This is probably something obvious and simple, but it's stumping me today. Here is the code I'm using:

= form.text_field :name, { required: true, class: "#{'error' if @project.errors[:name].present?}", placeholder: '40 characters max', maxlength: 40, :onkeyup => "countCharname(this)" }
span id="charName" class="margin-left-5"             

    function countCharname(val) {
      var len = val.value.length;
      if (len >= 40) {
        val.value = val.value.substring(0, 40);
      } else {
        $('#charName').text(40 - len);
      }
    };

Solution

  • Without testing it, my assumption is that when it reaches the max length, the input length is 40. This means that the if statement (len >= 40) is true, so the else statement, which updates the $('#charName') with the remaining characters, doesn't get run.

    Try changing the if statement to (len > 40)