Lisa Lisa - 4 days ago 5
Javascript Question

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);
});

Answer

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.

Comments