Ошибка javascript не определено не функция

I have this «Uncaught ReferenceError: function is not defined» error which do not understand.

If I have

$(document).ready(function() {
  function codeAddress() {
    var address = document.getElementById("formatedAddress").value;
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    });
  }
});

and

<input type="image" src="btn.png" alt="" onclick="codeAddress()" />
<input type="text" name="formatedAddress" id="formatedAddress" value="" />

When I press the button it will return the «Uncaught ReferenceError».

But if I put the codeAddress() outside the $(document).ready(function(){}) then it working fine.

My intention is put the codeAddress() within the document.ready function.

Ivar's user avatar

Ivar

5,98712 gold badges49 silver badges61 bronze badges

asked Feb 21, 2011 at 15:37

Peter's user avatar

2

The problem is that codeAddress() doesn’t have enough scope to be callable from the button. You must declare it outside the callback to ready():

function codeAddress() {
    var address = document.getElementById("formatedAddress").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
        }
    });
}


$(document).ready(function(){
    // Do stuff here, including _calling_ codeAddress(), but not _defining_ it!
});

answered Feb 21, 2011 at 15:42

Humberto's user avatar

HumbertoHumberto

7,0874 gold badges30 silver badges46 bronze badges

4

How about removing the onclick attribute and adding an ID:

<input type="image" src="btn.png" alt="" id="img-clck" />

And your script:

$(document).ready(function(){
    function codeAddress() {
        var address = document.getElementById("formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
            }
        });
    }
    $("#img-clck").click(codeAddress);
});

This way if you need to change the function name or whatever no need to touch the html.

answered Feb 21, 2011 at 15:49

ifaour's user avatar

ifaourifaour

38k12 gold badges72 silver badges79 bronze badges

3

Your issue here is that you’re not understanding the scope that you’re setting.

You are passing the ready function a function itself. Within this function, you’re creating another function called codeAddress. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).

For example:

var myfunction = function(){
    var myVar = 12345;
};

console.log(myVar); // 'undefined' - since it is within 
                    // the scope of the function only.

Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Another thing is that I notice you’re using jQuery on that page. This makes setting click handlers much easier and you don’t need to go into the hassle of setting the ‘onclick’ attribute in the HTML. You also don’t need to make the codeAddress method available to all:

$(function(){
    $("#imgid").click(function(){
        var address = $("#formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
           }
        });
    });  
});

(You should remove the existing onclick and add an ID to the image element that you want to handle)

Note that I’ve replaced $(document).ready() with its shortcut of just $() (http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I’ve also replaced your document.getElementById with the jQuery object.

answered Feb 21, 2011 at 15:57

Jonathon Bolster's user avatar

Jonathon BolsterJonathon Bolster

15.8k3 gold badges43 silver badges46 bronze badges

2

You must write that function body outside the ready();

because ready is used to call a function or to bind a function with binding id like this.

$(document).ready(function() {
    $("Some id/class name").click(function(){
        alert("i'm in");
    });
});

but you can’t do this if you are calling «showAmount» function onchange/onclick event

$(document).ready(function() {
    function showAmount(value){
        alert(value);
    }

});

You have to write «showAmount» outside the ready();

function showAmount(value){
    alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
    alert("will display on page load")
});

Vijay C's user avatar

Vijay C

4,7292 gold badges41 silver badges46 bronze badges

answered Feb 24, 2012 at 7:44

Taimoor Changaiz's user avatar

Taimoor ChangaizTaimoor Changaiz

10.2k4 gold badges49 silver badges53 bronze badges

One more thing. In my experience this error occurred because there was another error previous to the Function is not defined - uncaught referenceerror.

So, look through the console to see if a previous error exists and if so, correct any that exist. You might be lucky in that they were the problem.

answered Sep 28, 2020 at 18:17

Jeff's user avatar

JeffJeff

4314 silver badges16 bronze badges

Clearing Cache solved the issue for me or you can open it in another browser

index.js

function myFun() {
    $('h2').html("H999999");
}

index.jsp

<html>
<head>
    <title>Reader</title>
</head>
<body>
<h2>${message}</h2>
<button id="hi" onclick="myFun();" type="submit">Hi</button>
</body>
</html>

answered Jan 18, 2021 at 20:13

Akshay Sharma's user avatar

Sometimes it happens because of cache and cookies and the function that we created on the js file could not be loaded by the browser. So try to clear cache and cookies or press CTRL+F5 on the same page. Also, You can try to open it on incognito.

answered Oct 5, 2021 at 7:55

Kashish Kori's user avatar

please add the function outside the .ready function.

$(document).ready(function () {
   listcoming();
});

function listcoming() {}

Like this… it doesn’t have enough space and scope inside the .ready f

answered Apr 5, 2022 at 6:03

Shivam Kumar's user avatar

1

Please check whether you have provided js references correctly. JQuery files first and then your custom files. Since you are using ‘$’ in your js methods.

answered Jul 8, 2017 at 17:53

Nayanajith's user avatar

NayanajithNayanajith

6059 silver badges15 bronze badges

Thought I would mention this because it took a while for me to fix this issue and I couldn’t find the answer anywhere on SO. The code I was working on worked for a co-worker but not for me (I was getting this same error). It worked for me in Chrome, but not in Edge.

I was able to get it working by clearing the cache in Edge.

This may not be the answer to this specific question, but I thought I would mention it in case it saves someone else a little time.

answered Oct 30, 2020 at 17:40

Matt G's user avatar

Matt GMatt G

261 silver badge4 bronze badges

Just move the function to external js file as it is including $ code
This error will be resolved

answered Jan 9 at 7:08

Balasubramanian Ramamoorthi's user avatar

If you put the function between () it is a local function, so the function is only for that script.

(function (){
  // Local Function 
});

So if you delete the brackets, you will get a document function.

(function (){ 
  // Document Function 
});

And then you will be able to use the function in every script

answered Jan 9 at 17:12

user20967315's user avatar

You’re trying to call your JavaScript function. But, whenever you do, the result is a ReferenceError that goes like this:

// Call the function
myFunction();

// ReferenceError
Uncaught ReferenceError: myFunction is not defined

What went wrong? And how can you fix it?

Fear not; it happens to the best of us! The good news is that this ReferenceError is usually caused by one of the oversights that you and I will go through below. With a little investigation and debugging, you should be able to find the root cause in no time.

The Function Isn’t Defined at All

The most obvious—and, ironically, the most common—cause for the function not defined error is that, no prizes for guessing, the function isn’t defined in your code at all.

To save yourself hours of chasing a red herring, this is also the first probable cause you should rule out when debugging your code.

For those of you just getting started with JavaScript, here is a code snippet to illustrate what I mean:

// Define (or declare) the function
function saySomething(message) {
  console.log(message);
};

// Call the function
saySomething("The answer to life, the universe, and everything, is 42.");

Lines 2 through 4 define (or declare) our function. They consist of:

  • The function keyword
  • The name of the function, in our case saySomething
  • A list of the parameters it consumes (message)
  • The function’s statement between curly brackets {console.log(message)}

Only after we’ve defined our function properly can we call it with saySomething(), as shown on line 7.

The question is, what could be causing this?

Sanity-check #1:

If your function’s definition is supposed to be included within a <script> element in the HTML document, make sure that the script within the element (or the version of it that’s currently loaded in your app) actually contains it.

You might be testing against an older version of the document that doesn’t contain the function definition you need. Or you may be coming across caching issues, whether server- or client-side.

Sanity-check #2:

If your function’s definition is supposed to be included in an externally-hosted script, for example <script src="cdn.site.com/script.js"></script>, check if the URL of that script is correct, if the script is indeed there, and if the version of the script you need is what’s being returned by the CDN or server.

Once again, version control and/or caching are usually the culprits here. Identifying them early on can save you minutes, and sometimes hours, of dead-end debugging.

You’re Calling the Function Before It’s Defined

If the code that calls your JavaScript function precedes that function’s definition in your HTML document, you will come across the function is not defined error.

This is very, very important to check and rule out before you proceed to investigating other probable causes.

To build on the example above, suppose we’re developing a super-simple frontend for a web app using HTML5 and JavaScript.

It has two <script> elements: one that defines and function and one that calls it. However, we ordered them wrongly within our HTML markup; the call for the function precedes the definition of that function in our document:

<!doctype html>
<html lang="en-US">

<head>
  <meta charset="utf-8">
  <title>What's the answer to life?</title>
  <!-- Call function -->
  <script>
    populateAnswer("article.question-01 span.answer","The answer to life, the universe, and everything, is 42.");
  </script>
</head>

<body>
<article class="question-01">
<h1 class="question">Question: What's the answer to life?</h1>
<p>Answer: <span class="answer"></span></p>
</article>

<!-- Define function -->
<script>
  function populateAnswer(placeholder,answer) {
    document.querySelector(placeholder).innerHTML = answer;
  };
</script>
</body>

</html>

What’s happening here is that the browser, as it parses the HTML markup and interprets the JavaScript code, will try to call a function whose definition it hasn’t come across yet.

For this web app of ours to work, and to populate our <span class="answer"></span> element with the answer parameter, we need the function’s definition to come before the call:

<!doctype html>
<html lang="en-US">

<head>
  <meta charset="utf-8">
  <title>What's the answer to life?</title>
  <!-- Define function -->
  <script>
    function populateAnswer(placeholder,answer { document.querySelector(placeholder).innerHTML = answer; };
  </script>
  <!-- Call function -->
  <script>
    populateAnswer("article.question-01 span.answer","The answer to life, the universe, and everything, is 42.");
  </script>
</head>

<body>
<article class="question-01">
<h1 class="question">Question: What's the answer to life?</h1>
<p>Answer: <span class="answer"></span></p>
</article>
</body>

</html>

Sounds simple enough, doesn’t it?

Add a content management system like Drupal or WordPress to the mix and throw in a tag manager like Google Tag Manager or Adobe Launch, and it isn’t hard to see just how many things can go wrong by scripts being injected in the wrong sequence.

Sanity-check #1:

Where’s the <script> element that has your function’s definition? Pay special attention to scripts loaded in the <body>, whether at the start, in the middle, and especially down in the footer for performance reasons.

Are you trying to call the function before the definition? Remember that browsers have no memory for this, and will throw back a ReferenceError when it happens.

Sanity-check #2:

There’s a great deal of Google PageSpeed optimization tools out there nowadays, from Ezoic’s Leap for publishers to NitroPack for pretty much everyone else to all sorts of plugins, free and paid, for WordPress.

Almost all of these tools let you delay the execution of scripts until the DOM has finished loading. Although this improves your Google PageSpeed score, but can create issues for scripts that contain definitions of functions you’re calling within the DOM to write HTML elements directly into it.

Sanity-check #3:

Are you using a VPN? It’s not uncommon for CDNs and hosting providers to block the IPs of some of the most popular VPN apps out there, as they’re frequently used for attacks, fraud, and spam.

Disable your VPN and see if the problem persists. The JavaScript with the function’s definition might all of a sudden start loading. 🙂

Mistyped Name or Errors in Function

Burning the midnight oil to get the job done?

You’re more likely to make mistakes like mistyping your function’s name:

// Function definition
function myFunction(sayThis){ console.log(sayThis) };

// Mistyped name with lowercase letter
function myfunction("What's my name?");

// Mistyped name with typo
function myFuntion("What's my name?");

// Right name, no ReferenceError
function myFunction("That's my name!");

Sanity-check #1:

Check the name of your function. Is it spelled correctly? Now check if you’re calling that function with the right name, and whether you misspelled it in any way, including lowercase/uppercase characters.

Or omit parentheses in parameters, brackets in arrays, braces at the start and end of statements, and semi-colons wherever necessary:

// Forgot opening or closing parenthesis for the function's parameters
function myFunction(sayThis{console.log(sayThis) };

// Forgot opening or closing braces for the function's statement
function myFunction(sayThis){console.log(sayThis) ;

// Added extra brace at the start or end of the function's statement
function myFunction(sayThis){console.log(sayThis) }};

You can quickly uncover these oversights by checking for errors in your browser’s console. If you encounter an error message that says “myFunction is not a function” or that “this was expected instead of that,” you know you need to look closely at the code to see where you made a mistake.

Sanity-check #2:

Evaluate the browser’s console for errors. If you come across any related to your function, debug the function and fix whatever mistake(s) you made.

In Conclusion

Thank you for reading this far and I hope this helped.

Nine times out of ten, the biggest issues are caused by the smallest mistakes. (Which, since we’re human, we’re prone to making, especially when under time pressure and emotional stress.)

Whenever you come across a ReferenceError for your JavaScript function, check if it’s declared and, if the answer is “yes,” whether it’s declared and called in the right sequence. When you’ve ruled these out, chances are high that a mistyped name or error in the function are the root cause; investigate accordingly.

Image courtesy of alphaspirit /Depositphotos

Sometimes, you may come across JavaScript function is not defined error that looks like the following:

Uncaught ReferenceError: doAction is not defined

The ReferenceError as in the case above is caused when you call something that’s not defined in JavaScript. Let me show you several things you can do to fix the error.

Make sure the function is defined inside your script

One of the small mistakes that could cause the error is that you haven’t defined the function properly. You need to define the function using either the function keyword:

function doAction() {
  // your function code here
}

Or using the arrow function syntax as follows:

const doAction = () => {
  // your function code here
};

Please keep in mind that functions defined through function expressions must be defined before the call. Function expressions are functions that you defined through a variable keyword as follows:

var fnAction = function () {};
// or
let fnAction = () => {};

From the example code above, the variable fnAction will be hoisted, but the function declaration is not, so it will be undefined as shown below:

fnAction(); // fnAction is not defined
let fnAction = () => {
  console.log("Executing action");
};

See also: JavaScript hoisting behavior

That’s why it’s always better to define the function before calling it.

When you have defined the function, try calling it immediately below the declaration to see if it works:

function doAction() {
  // your function code here
}

doAction(); // test the function call

If it’s running without any error, then you may have several lines of code after the declaration that causes the script to malfunction.

Make sure the entire script has no error

If you’re putting the function into a script and calling it from an HTML tag, you need to make sure that the entire script has no error or the function won’t be loaded.

For example, notice how there is an extra ) right next to getElementById call:

<!DOCTYPE html>
<html>
  <head>
    <title>Function not defined</title>
  </head>
  <body>
    <button id="action" onclick="fnAction()">Click me</button>
    <script type="text/javascript">
      document.getElementById("action")); // extra ')' here
      function fnAction(){
        console.log("Executing action");
      }
    </script>
  </body>
</html>

Although there’s no error on the fnAction() code, an error in any part of the script will cause the browser to ignore the rest of that script. You need to fix the error first so the rest of the code can be executed by the browser.

One way to see if you have any error is to run the HTML page and check on the console as follows:

You may find the ReferenceError fixed itself as you fix JavaScript errors from your scripts.

Make sure the script is loaded before the call.

Finally, the function is not defined error can also be caused by calling the function before the script is loaded to the browser. Suppose you have a JavaScript file separated from your HTML file as follows:

// script.js
function fnAction() {
  console.log("executing action");
}

Then you load the script into your HTML file, but you call the fnAction function before you load the script as follows:

<body>
  <h1>Load script demo</h1>
  <script type="text/javascript">
    fnAction();
    // Uncaught ReferenceError: fnAction is not defined
  </script>
  <script src="script.js"></script>
</body>

The same also happens when you call it on the <head> tag:

<head>
  <title>Function not defined</title>
  <script type="text/javascript">
    fnAction();
  </script>
  <script src="script.js"></script>
</head>

To fix this, you need to call the function below the <script src="script.js"></script> call:

<head>
  <title>Function not defined</title>
  <script src="script.js"></script>
  <script type="text/javascript">
    fnAction();
  </script>
</head>

Those are the three ways you can try to fix function is not defined error in JavaScript.

Время на прочтение
1 мин

Количество просмотров 42K

Джаваскриптовая ошибка «undefined is not a function» довольно загадочна. Как раз поэтому определённым спросом пользуются разъяснительные статьи, из которых читатель, начинающий изучать программирование на JavaScript, способен узнать о том, что такая ошибка (попытка использовать неопределённое значение как функцию) чаще всего возникает при вызове несуществующего метода объекта (а такой вызов, в свою очередь, чаще всего происходит в случае опечатки в названии метода). Такой разъяснительной статьёю может послужить «Ошибки в JavaScript и как их исправить», например.

Однако и после разъяснений остаётся мысль о том, что обнаружение и устранение опечаток (да и других оплошностей при вызове методов) было бы много проще, если бы название «виновного» метода содержалось непосредственно в тексте появляющейся ошибки.

Так и вышло:

Improved exception messages: Goodbye «undefined is not a function». Hello «http://t.co/rMIELG5VoW is not a function» pic.twitter.com/3uykfrTK9O

— Addy Osmani (@addyosmani) 21 февраля 2015

Впрочем, вышеозначенное улучшение сообщения об ошибке произошло только в V8, то есть появится оно только в Google Chrome, в Chromium, в новой Опере, а со временем — в Node.js и в других нодоподобных движках, служащих для запуска внебраузерного джаваскрипта. О внедрении подобного улучшения в остальных браузерах ничего не известно.

I call my JavaScript function. Why do I sometimes get the error ‘myFunction is not defined’ when it is defined?

For example. I’ll occasionally get ‘copyArray is not defined’ even in this example:

function copyArray( pa ) {
    var la = [];
    for (var i=0; i < pa.length; i++)
        la.push( pa[i] );
    return la;
}

Function.prototype.bind = function( po ) {
    var __method = this;
    var __args = [];

    // Sometimes errors -- in practice I inline the function as a workaround.
    __args = copyArray( arguments );

    return function() {
        /* bind logic omitted for brevity */
    }
}

As you can see, copyArray is defined right there, so this can’t be about the order in which script files load.

I’ve been getting this in situations that are harder to work around, where the calling function is located in another file that should be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.

It doesn’t happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.

@Hojou: That’s part of the problem. The function in which I’m now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.

@James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the ‘not defined’ error.

@David: The script in this case resides in an external file that is referenced using the normal <script src=»file.js»></script> method in the page’s head section.

@Douglas: Interesting idea, but if this were the case, how could we ever call a user-defined function with confidence? In any event, I tried this and it didn’t work.

@sk: This technique has been tested across browsers and is basically copied from the Prototype library.

Понравилась статья? Поделить с друзьями:
  • Ошибка javascript в google chrome
  • Ошибка java не запускается minecraft
  • Ошибка javascript error occurred in the main process дискорд
  • Ошибка java на кнопочном телефоне
  • Ошибка javascript error occurred in the main process skype