Skip to content Skip to sidebar Skip to footer

Why Does My Counter Not Work In The Field Like I Would Expect

I have implemented a JS counter in my app. I have 2 form fields that my two different counters should work for. A #post_title and a #body-field. This is my JS: The seemingly stray

Solution 1:

You should not have the counter function check and perform operations on both fields. The counter function should do exactly the same operation, by utilizing jquery's this keyword inside it, or by taking an event parameter and using that as an alternative, with event.target.

Here's the refactor:

var counter = function(event) {
    var fieldValue = $(this).val();
    var wc = fieldValue.trim().replace(regex, ' ').split(' ').length;
    var regex = /\s+/gi;
    var $wcField = $(this)[0] === $('#post_title')[0] ? $('#wordCountTitle') : $('#wordCountBody');

    if (fieldValue.length === 0) {
        $wcField.html('');
        return;
    }

    $wcField.html(wc);
};

$(document).on('ready page:load', function () {
    $('#post_title, #body-field').on('change keyup paste', counter);
});

JSBin playground

Also, I am not entirely sure why you are listening to that many events on those textareas, when change keyup paste ought to do it.

Solution 2:

the error you're having is because of these 2 blocks of code

if (title_value.length == 0) {
    $('#wordCountTitle').html(0);
    return;
}

if (body_value.length == 0) {
    $('#wordCountBody').html(0);
    return;
}

This means that in order for the counters to run, both title and body should have some value. Just remove the return on both and it should work.

EDIT

I think removing both if blocks will also give you the same behavior you want. If you want to have both if blocks, you'll have to separate the counter for the title and body.

EDIT 2

here's a simpler implementation of counter function.

counter = function() {
  var title_value = $('#post_title').val();     
  var body_value = $('#body-field').val();

  $('#wordCountTitle').html(title_value.split(' ').length);
  $('#wordCountBody').html(body_value.split(' ').length);
}

Post a Comment for "Why Does My Counter Not Work In The Field Like I Would Expect"