Search code examples
javascripthtmlmediawikireferenceerror

Uncaught ReferenceError: *function here* is not defined


Uncaught ReferenceError: limitText is not defined

Just from the number of matching results, I see numerous other people have had this issue - Though the solution runs on a case-by-case basis.

This is basically a function for telling you how many character you have left in a given form as you type - "You have XXX character left".

Javascript:

"use strict"; // <-- This was a suggested remedy, did nothing.
function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}

HTML (Unrelated PHP omitted):

<textarea name="BlogPost" maxlength="5000" cols="100" rows="20" 
onKeyDown="limitText(this.form.BlogPost,this.form.countdown,5000);" 
      onKeyUp="limitText(this.form.BlogPost,this.form.countdown,5000);" required></textarea>
   <font size="1">(Maximum characters: 5000)<br>
   You have <input readonly type="text" name="countdown" size="3" value="5000">
   characters left.</font>

Putting my browser into "Debug Mode" actually causes the script to work without error - Though I genuinely cannot expect any user running the app to do the same. It also works if the script is placed directly into the document with <script></script>, though the system I'm working with scolds that as being "bad practice" as you're expected to load scripts through it's fancy module system. (Mediawiki)

Any ideas?


Solution

  • First iteration with onKeyDown and onKeyUp (you missed form element) – http://jsfiddle.net/3ZAeP/

    code

    (function (global) {
        global.limitText = limitText;
        function limitText(limitField, limitCount, limitNum) {
            if (limitField.value.length > limitNum) {
                limitField.value = limitField.value.substring(0, limitNum);
            } else {
                limitCount.value = limitNum - limitField.value.length;
            }
        }
    }(window));
    

    It's interesting as limitText should be global out of box.