Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable into a function in javascript

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);
});
like image 251
Person Avatar asked Apr 17 '26 10:04

Person


1 Answers

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.

like image 83
Rory McCrossan Avatar answered Apr 18 '26 23:04

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!