Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
One of my cshtml pages has javascript that is not firing, each function has an alert at line 1 to show if it is hit, the debugger is not picking it up either.
My objective is to validate that a correctly formatted email has been entered. Two of the functions are attempting this, the third is just a test function to try a simple call.

The source here is the product of View source on firefox:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>VT IdentityServer4</title>
    <link rel="icon" type="image/x-icon" href="/favicon.ico" />
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.css" />
    <link rel="stylesheet" href="/css/site.css" />
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a href="/">
                    <span class="navbar-brand">
                        <img src="/icon.png" class="icon-banner">
                        IdentityServer4
                    </span>
                </a>
            </div>

        </div>
    </div>

    <div class="container body-content">
        <form action="/Account/ForgotPassword" enctype="multipart/form-data" method="post">    <div class="panel-body">
        <div class="bg-info p-2"><h4>Reset Password</h4></div>


        <div class="form-group">
            <label for="UserMaster_Email">Email</label>
            <input class="form-control" id="userEmail" type="text" name="UserMaster.Email" value="" />
        </div>


        <div>
            <h1> Click the button to send a  link  to the email address provided, please follow it to set a new password</h1>
        </div>
        <input id="returnUrl" name="returnUrl" type="hidden" value="/connect/authorize/callback?client_id=TestMVC&amp;redirect_uri=https%3A%2F%2Flocalhost%3A6001%2Fsignin-oidc&amp;response_type=code%20id_token&amp;scope=openid%20profile%20api1%20offline_access&amp;response_mode=form_post&amp;nonce=636971655198350102.NWE0NzZmOWEtY2M5OC00ZjY1LTgxZDQtYmRlYmFjM2Q4YzNiMDZlNGZlYTYtZmVmYS00OGQ0LWExYzUtYTQ1OGFjOTQxNWQ1&amp;state=CfDJ8PEC9PhnSjdGtGv-XdyPnE4sVD_NeakVMhCbPrEa2B0iSvRIlopzw-1Piyf5uqzjvHcBx5c-GyCRCHLxm5zQDgEmG4siDJ0bNev0l0c234qNcEIoo2NVebVdBjt6Aq_1pFx5dlTT0zCC_SQhpgD2j-Y6xdMaS-iRPbN6N8nRxpVajdjNbWSR76VLpa0R5aXQJyc1Fq2qi8i8V688UeUb303FMFodSfu_s95_V-0ck3Nj5OPSbTx6DfDugn5yiOvPJj_4Tj7T0DoHvHNCBY8gVr1Qw4ScdztkXaH5sjB8gpGo0dN3HVZd8CYrL0zMkW5qAm9aI1zA4At_36lL1iwbbRQ&amp;x-client-SKU=ID_NETSTANDARD2_0&amp;x-client-ver=5.3.0.0" />

        <div class="panel-footer">
            <div class="form-group">
                <button class="btn btn-primary" name="button" value="sendLink" id="sendLinkBtn" onclick="emailChanged()">Send Password Reset Link</button>
                <button class="btn btn-default" name="button" value="cancel" onclick="myFunction()">Cancel</button>
            </div>
        </div>
    </div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8PEC9PhnSjdGtGv-XdyPnE6FpWkPfrGjWXYXJ-hIvJbveurwqgucguTju-4mETob6dBOzE0PnOGqCJEwE6JTkf7FqOo8thhm_3m5Uvh4tY8WhmH-rbeg0rzjAtIggwXp8dcE3NwKiehtMYWUaayKp0Y" /></form>
<script  type="text/javascript">
    function myFunction() {
//        var x = document.getElementById("userEmail").innerHTML = "Hello World";
        alert("The text has been changed3.");
    }
    function emailChanged() {
        alert("The text has been changed2.");
        var hasError = false;
        var emailReg = /^([\w-\.]+@([\w -] +\.)+[\w-]{2,4})?$/;

        var emailaddressVal = $("#UserMaster.Email").val();
        if (emailaddressVal == '') {
            $("#UserMaster.Email").after('<span class="error">Enter email address.</span>');
            hasError = true;
        }

        else if (!emailReg.test(emailaddressVal)) {
            $("#UserMaster.Email").after('<span class="error">Enter a valid email address.</span>');
            hasError = true;
        }

        if (hasError == true) { return false; }


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

        $('#sendLinkBtn').click(function () {
            alert("The text has been changed1.");
            $(".error").hide();
            var hasError = false;
            var emailReg = /^([\w-\.]+@([\w -] +\.)+[\w-]{2,4})?$/;

            var emailaddressVal = $("#UserEmail").val();
            if (emailaddressVal == '') {
                $("#UserEmail").after('<span class="error">Enter email address.</span>');
                hasError = true;
            }

            else if (!emailReg.test(emailaddressVal)) {
                $("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
                hasError = true;
            }

            if (hasError == true) { return false; }

        });
    });
</script>

    </div>

    <script src="/lib/jquery/jquery.js"></script>
    <script src="/lib/bootstrap/js/bootstrap.js"></script>
    
</body>
</html>

This is not normally difficult. Any thoughts on what I may have missed

What I have tried:

The code included in the question shows my different attempts and here is one of the online examples that I have followed. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick
Posted
Updated 26-Jun-19 8:42am
Comments
Richard Deeming 26-Jun-19 13:29pm    
Your script relies on jQuery, but jQuery isn't included until after your script.

Try moving the jQuery includes above your script block.

1 solution

Most probably you code has to fail around this line,
var emailaddressVal = $("#UserMaster.Email").val();
But that requires everything else is fine and console doesn't show any "undefined" errors.
Quote:
each function has an alert at line 1 to show if it is hit, the debugger is not picking it up either.
Oh boy, you are doing it the wrong way. Use Chrome Developer Tools and set breakpoints in your local environment, instead of polluting the code with alerts that might move to production. If the debugger is not hitting that means that something is not letting the code to reach at this point, maybe incorrect naming of the connections between the elements and scripts, or perhaps something worse.

And the solution as Richard has suggested already, you need to move the jQuery inclusion in your HTML DOM to the top—jQuery always goes as the first script in the DOM. This one,
HTML
<script src="/lib/jquery/jquery.js"></script>
<script src="/lib/bootstrap/js/bootstrap.js"></script>
Also, check that you are loading everything that needs to be loaded before you execute any dependent code, one of such codes is the $(document).ready(function () { }); code, check that too.

If the code still doesn't work, the error would be printed in the console, please share that to be precise about the solution.
 
Share this answer
 
Comments
Ger Hayden 27-Jun-19 1:10am    
Thanks Afzaal, Plenty to work with there. This is a page I bolted onto on of the Identity Server examples and the bootstrap / jquery calls are being pulled in automatically.

This is the last part of the _layout.chstml:

@RenderBody()




@RenderSection("scripts", required: false)



My script code was comming in as part of the body rather than the scripts section.

I have corrected that and reduced the function body in each case to just the alert with no success, and when I put it into chrome I see this error:
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-UT3bVGIVpElFF57vLK9xLpaZaM/Mf01HLSt+X8TN2EA='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

It will probably be tomorrow, but I will move the scripts out to their own file and see how that goes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900