42

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
  • 6,138
  • 12
  • 49
  • 61
Peter
  • 1,481
  • 4
  • 19
  • 37

12 Answers12

58

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!
});
Humberto
  • 7,117
  • 4
  • 31
  • 46
  • Thanks Humberto, I now have more understanding on the javascript. Thanks of your kind explanation. – Peter Feb 21 '11 at 16:04
  • 2
    This! This was the answer to my problem because I was not able to run my own functions (not-related to jQuery), and as soon as I put them before the `jQuery(document).ready(function() {` then everything worked! Thanks, Humberto! – ipruthi Jan 02 '13 at 02:30
  • 1
    Thank you, this answer make me understand jquery and js – Tarek Kalaji Jan 06 '16 at 11:07
  • Perfect answer. Solved my problem, `function was undefined` – TheTechGuy Jan 27 '19 at 16:29
44

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.

ifaour
  • 38,035
  • 12
  • 72
  • 79
  • 1
    @ifaour What should I do, if I want to pass a parameter to the `codeAddress()` function? – V15HM4Y Jun 17 '13 at 11:51
  • 1
    Removing the `onclick` isn't a going to be helpful all the time. I am creating a few elements dynamically and would want them to call a function when clicked. I can't achieve this with the method you have mentioned. Your's is an alternative not a solution for the question. – Hari Harker Oct 24 '16 at 14:01
  • This would be helpful if all of the other methods weren't also defiend in the ready section. This is becoming a bit of a head ache because of nesting views, we have to use document ready, but can be accessed inside that was declared outside. – Urasquirrel Mar 22 '21 at 16:07
26

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.

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
18

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
  • 4,739
  • 4
  • 41
  • 46
Taimoor Changaiz
  • 10,250
  • 4
  • 49
  • 53
1

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.

Jeff
  • 431
  • 4
  • 16
1

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>
1

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.

1

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

  • please correct your answer so that your code section is correctly displayed. It will help by providing more clarity? – mtholen Apr 05 '22 at 07:55
0

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.

Nayanajith
  • 605
  • 10
  • 15
0

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.

Matt G
  • 26
  • 1
  • 4
-1

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

-1

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