user1321237
user1321237

Reputation:

My javascript function cannot be found

I have the following:

$(function () {

    $.ajaxSetup({ cache: false });
    var dialogs = {};

    var formSubmitHandler = function (e) {
        ...
    }

}

then in another script I try to call

function dialogClick(link) {

    $.get(viewUrl + parameters)
            .success(function (content) {
                if (content.match(/^[eE]rror/)) {
                    mvcOnFailure(data)
                } else {
                    $.modal({
                        title: title,
                        closeButton: true,
                        content: content,
                        width: false,
                        resizeOnLoad: true
                    }).find('form').submit(formSubmitHandler).end();
                }
            })

Note that I have cut out parts of the script to make it easy to read. There are no script errors showing just the following error:

In the second script I get an error message saying "SCRIPT5009: 'formSubmitHandler' is undefined' in Internet Explorer.

Am I calling it wrongly? I thought the function would be global and when I check the script that it is inside of is attached to the page.

Upvotes: 2

Views: 240

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

formSubmitHandler is a function declared in a scope not visible for the dialogClick() function

So

  • Either you declare formSubmitHandler as global
  • or you define the function dialogClick inside document.ready function (and formSubmitHandler is reachable since is in a parent scope)

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108530

formSubmitHandler only exists within the function scope you declare it, since you used the var variable.

You need to either:

  1. declare dialogClick in the same scope
  2. declare formSubmitHandler in the global scope, using window.formSubmitHandler or simply function formSubmitHandler(){}

Upvotes: 0

tuscan88
tuscan88

Reputation: 5839

Try moving your function out of the function block e.g

$(function () {

    $.ajaxSetup({ cache: false });
    var dialogs = {};
}

var formSubmitHandler = function (e) {
    ...
}

Upvotes: 0

Pointy
Pointy

Reputation: 414036

No, it's not global; your "formSubmitHandler" function is declared within the "ready" callback in the first block of sample code you posted. It's therefore private to that function.

What you could do, if you really want a global function, is:

window['formSubmitHandler'] = formSubmitHandler;

in the first function. Or, alternatively, you could make it a jQuery "global" function:

$['formSubmitHandler'] = formSubmitHandler;

In that case, you'd get to it as $.formSubmitHandler.

Upvotes: 7

Related Questions