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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much Rory!! I definitely didn't know about the falsy logic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.