We can easily debug C# code using breakpoints but when we want to debug JavaScript code then we need to make some extra effort. I explain in this article step-by-step how to debug JavaScript code defined in a .aspx page using Visual Studio and Internet Explorer so let's see that now.
Step 1 : Create a WebForm
We create a webform that has a JavaScript function called on a button click. Here we have SquareNumber(), a JavaScript function that squares a value that is then inserted in TextBox by the user on a button click and shows the resulting value in an alert box.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type ="text/javascript">
function SquareNumber()
{
var number = document.getElementById("<%=txtNumber.ClientID %>").value;
alert(number +" square is :"+ number*number);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter a Number : <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
<asp:Button ID="btnSquare" runat="server" Text="Square" OnClientClick="SquareNumber()" />
</div>
</form>
</body>
</html>
Step 2 : Setting in IE to enable debug
- Go to "Tools" - "Internet Option"
- Go to the "Advanced" tab - "Browsing" then uncheck "Disable Script Debugging" then click "OK".
Step 3 : Insert breakpoint
We insert the breakpoint where the pointer will hit directly.
Step 4 : Run the applications (press the F5 Key)
When we run the application then the following web page is shown and then insert a value into the TextBox.
Click on the "Square" button:
Get the output:
Step 5 : Insert debugger
When we insert the JavaScript debugger then the code will be started from the debugger and will proceed line by line; in this case we don't need to insert a breakpoint. We only need to write debugger in a JavaScript function where we start the debug code.
Press the F10 key to move to the next line.
NOTE : Remove the JavaScript debugger before publishing or releasing a website or web application.
In the next article I explained that how can debug JavaScript using Google Chrome, that article is:
Debugging JavaScript Using Google Chrome