3

I'm not sure what is wrong with my code. I keep getting A NaN variable for maxLength. Am I writing this function correctly?

Helper function I am trying to call:

(function($) {
    $.fn.countRemainingCharactersHelper = function(maxLength) {
        id = this.attr('id');
        var textLength = this.val().length;
        var textRemaining = maxLength - textLength;

        if (textLength >= maxLength) {
            textRemaining = 0;
        }

        var messageId = id.slice(0, (id.indexOf('someTxtBox'))) + 'someTxtBox';
        $('#' + messageId).html(textRemaining + ' characters remaining.');
    };
})(jQuery);

Functions calling to the helper function above:

function countRemainingCharacters() {
    $(this).countRemainingCharactersHelper(1000);
}

function countRemainingCharacters(maxLength) {
    $(this).countRemainingCharactersHelper(maxLength);
}

Calling to function passing in the maxLength variable

$('#samplesomeTxtBox').click(function() {
    countRemainingCharacters(4000);
});
0

1 Answer 1

4

this will refer to the window in your countRemainingCharacters() functions as you don't call it with a scope. You can fix that using call():

$('#samplesomeTxtBox').click(function() {
    countRemainingCharacters.call(this, 4000);
})

Also note that the logic you use to generate the id of the element to place the message in is a little off. You could improve it by using a data attribute to explicitly set the element id.

Your overloaded method is also redundant in this case as you can take advantage of JavaScripts 'falsy' logic to provide a default value if none was provided. This means that you can convert your two countRemainingCharacters() functions in to one:

function countRemainingCharacters(maxLength) {
    $(this).countRemainingCharactersHelper(maxLength || 1000);
}

Working example

All that would be left at that point is to create a key event handler to calculate the remaining characters as the user types.

1
  • Thank you so much Rory!! I definitely didn't know about the falsy logic.
    – Person
    Jul 7, 2016 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.