Getting error: val is undefined. Why?

Getting error: val is undefined. Why?

Hi.
I get this error when I load my page:
Error: val is undefined
Source: http://www.example.com/user/library/jav ... nctions.js
Line: 177

#177| eval(substringFunction);

The complete function is a plugin that counts characters in a textarea:
(function($){
     $.fn.extend({ 
         limit: function(limit,element) {
         
         var interval, f;
         var self = $(this);
               
         $(this).focus(function(){
            interval = window.setInterval(substring,100);
         });
         
         $(this).blur(function(){
            clearInterval(interval);
            substring();
         });
         
         substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
         if(typeof element != 'undefined')
            substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
            
         substringFunction += "}";
         
         eval(substringFunction);
         
         
         substring();
        }
    });
})(jQuery);


What's wrong with that? I even put the selector in its own if clause, so that it doesn't get called when there is no textarea.
if( $.fn.limit ) {
      $('#userFreeText').limit('250','#charsLeft');
   }


That error makes everything beneath that code doesn't work. Need some help please.