1

I want to test a simple JavaScript function in ASP.NET.

Movies/Index.cshtml

<!-- My local JavaScript File -->
<script src="~/Scripts/JavaScript.js" type="text/javascript"></script>

<input type="button" id="getPeople" value="Get People"/>
<ul id="people_list"/>

Views/Shared/_Layout.cshtml

<script src="~/Scripts/jquery-2.2.3.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="~/Scripts/JavaScript.js" type="text/javascript"></script>

/Scripts/JavaScript.js

$(document).ready(function () 
{

});

$('#getPeople').click(function () 
{
    alert("getPeople");
}

I press the button but no alert appears. Why?

3
  • 1
    Because you are loading your javascript file before the #getPeople element, your click handler needs to be within the doc.ready block. Not after it. Is the unclosed click handler a copy-paste error or your actual code? Commented Nov 7, 2016 at 12:30
  • Is the click handler really outside of ready handler? If so, put it inside and that should do it Commented Nov 7, 2016 at 12:30
  • $(document).ready(function () { //Populate Contact //LoadContacts(); $('#getPeople').click(function () { alert("getPeople"); }); This not works Commented Nov 7, 2016 at 12:40

2 Answers 2

3

The click handler of '#getPeople' should be inside $(document).ready

$(document).ready(function () 
{
    $('#getPeople').click(function () 
    {
        alert("getPeople");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Make sure

  • to import jQuery first (before importing /Scripts/JavaScript.js)
  • to add click handler inside document's ready event.

Check the output of your composed page (for example Developer tools in the browser), if you are uncertain.

$(document).ready(function () {
    $('#getPeople').click(function () {
        alert("getPeople");
    });
});

Comments

Your Answer

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.