3

If I declare a function inside document.ready, I get an error. Like this

$(document).ready(function(){
 function updateSizeOptions()
 {
 alert("updateSizeOptions");
 }
 var jGrid = $("#list_main");
 jGrid.jqGrid({
 url:'db.php?ajaxOp=getData',
 colModel:[
 $.extend(true,
 { name:'shape_id'
 ,index:'shape_id'
 ,edittype:'select'
 ,formatter:'select'
 ,editoptions: { onclick:"javascript:updateSizeOptions();" }
 }
 ,{}
 ]
 ....
});

It will give Error : "ReferenceError: updateSizeOptions is not defined".
But If I moved the function outside document.ready, everything works fine.
Like this

function updateSizeOptions()
{
 console.debug("updateSizeOptions");
}
$(document).ready(function(){
 var jGrid = $("#list_main");
....

WHY ?

asked Nov 19, 2012 at 14:26

3 Answers 3

10

Because in Javascript, functions declared within other functions are local references, and are not visible outside the scope of their parent function. If you want to make your updateSizeOptions function globally accessible, you will need to assign a reference to it in a global namespace, say a window property:

window.updateSizeOptions = updateSizeOptions;
answered Nov 19, 2012 at 14:29
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh.. I got it. Because jqgrid plugin can't find the function in the global scope when making the grid. Oh man.. It cost me a day ! Thanks very much
0

Because you defined the function updateSizeOptions inside the anonymous function passed to $(document).ready, updateSizeOptions will only be available inside that anonymous function unless you export it. (i.e. window.updateSizeOptions = updateSizeOptions)

Functions (or/and variables) defined in the global scope is literally defined under the window object, so if you define the function in the global scope and you do alert(window.updateSizeOptions) you will see it shows a function. window.updateSizeOptions == updateSizeOptions will return true.

However if you define it inside a local scope, you will see undefined.

answered Nov 19, 2012 at 14:33

Comments

0

Scope. When you put something inside $(document).ready, the code will only be excecuted when this event is triggered and the things like variables and functions declared inside the event do not exist outside of the event unless set globally.

When you do javascript:updateSizeOptions(); it will look for a function in the global scope that in this case does not exist, therefor undefined.

answered Nov 19, 2012 at 14:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.