BernardWong
BernardWong

Reputation: 77

Javascript ReferenceError: function is not defined but it is

I have checked the code, but I can't find anything wrong.

<!-- language: lang-html -->

<div class="modal fade" id="loginModal" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div id="loginHeader" class="modal-header">
                <h4 class="modal-title">Oops, something not right.</h4>
            </div>
            <div id="loginContent" class="modal-body" runat="server">
            </div>
            <div id="loginButton" class="modal-footer">
                <button type="button" class="btn btn-warning" data-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
    <button type="button" style="display: none;" id="btnShowLoginModal" data-toggle="modal" data-target="#loginModal">
    </button>
</div>
<script src="../Scripts/javascripts/jquery.js"></script>
<script src="../Scripts/javascripts/bootstrap.min.js"></script>
<script type="text/javascript">
    function ShowLoginDialog() {
        $("#btnShowLoginModal").click();
    }
</script>

The function is called from code behind on OnClick Event. Still no clue which part is wrong.

protected void Button1_Click(object sender, EventArgs e)
{
    string result = ValidateLogin(Username.Value, Password.Value);

    if(result == MessageConstants.MessageSuccess)
    {
        Response.Redirect("~/Webpages/Character.aspx");
    }
    else if(result == MessageConstants.MessageFail)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "ShowLoginDialog()", true);
    }
    else
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "ShowLoginDialog()", true);

    }
}

Error from Element Inspector enter image description here

Upvotes: 1

Views: 820

Answers (3)

Kevin Collins
Kevin Collins

Reputation: 1461

RegisterStartupScript() emits the script block at the end of the Web Form (right before the </form> tag). source

But your modal code, and the ShowLoginDialog function are defined after that. Try moving that </form> tag to the end, after the modal stuff.

Upvotes: 2

Lennholm
Lennholm

Reputation: 7460

Move

<script src="../Scripts/javascripts/jquery.js"></script>
<script src="../Scripts/javascripts/bootstrap.min.js"></script>
<script type="text/javascript">
    function ShowLoginDialog() {
        $("#btnShowLoginModal").click();
    }
</script>

into the head block. Then you need to change the ShowLoginDialog function so that it looks like this:

function ShowLoginDialog() {
    $(function() {
        $("#btnShowLoginModal").click();
    });
}

Upvotes: 0

flowest
flowest

Reputation: 173

Put your code in the document.ready() function:

$( document ).ready(function() {
    function ShowLoginDialog() {
        $("#btnShowLoginModal").click();
    }
});

Upvotes: 0

Related Questions