Lisa Lisa - 1 year ago 72
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.');

Functions calling to the helper function above:

function countRemainingCharacters() {

function countRemainingCharacters(maxLength) {

Calling to function passing in the maxLength variable

$('#samplesomeTxtBox').click(function() {

Answer Source

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() {, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download