Libraries Search
Showing posts with label JAVA SCRIPT. Show all posts
Showing posts with label JAVA SCRIPT. Show all posts

Debugging JavaScript - library82.blogspot.com

Every now and then, developers commit mistakes while coding. A mistake in a program or a script is referred to as a bug.

The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks..

Error Messages in IE
The most basic way to track down errors is by turning on error information in your browser. By default, Internet Explorer shows an error icon in the status bar when an error occurs on the page.

Error Icon
Double-clicking this icon takes you to a dialog box showing information about the specific error that occurred.

Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show the Error dialog box whenever an error occurs.

To enable this option, select Tools → Internet Options → Advanced tab. and then finally check the "Display a Notification About Every Script Error" box option as shown below −

Internet Options
Error Messages in Firefox or Mozilla
Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window called the JavaScript Console or Error Consol. To view the console, select Tools → Error Consol or Web Development.

Unfortunately, since these browsers give no visual indication when an error occurs, you must keep the Console open and watch for errors as your script executes.

Error Console
Error Notifications
Error notifications that show up on Console or through Internet Explorer dialog boxes are the result of both syntax and runtime errors. These error notification include the line number at which the error occurred.

If you are using Firefox, then you can click on the error available in the error console to go to the exact line in the script having error.

How to debug a Script
There are various ways to debug your JavaScript −

Use a JavaScript Validator
One way to check your JavaScript code for strange bugs is to run it through a program that checks it to make sure it is valid and that it follows the official syntax rules of the language. These programs are called validating parsers or just validators for short, and often come with commercial HTML and JavaScript editors.

The most convenient validator for JavaScript is Douglas Crockford's JavaScript Lint, which is available for free at Douglas Crockford's JavaScript Lint.

Simply visit that web page, paste your JavaScript (Only JavaScript) code into the text area provided, and click the jslint button. This program will parse through your JavaScript code, ensuring that all the variable and function definitions follow the correct syntax. It will also check JavaScript statements, such as if and while, to ensure they too follow the correct format

Add Debugging Code to Your Programs
You can use the alert() or document.write() methods in your program to debug your code. For example, you might write something as follows −

var debugging = true;
var whichImage = "widget";

if( debugging )
alert( "Calls swapImage() with argument: " + whichImage );
var swapStatus = swapImage( whichImage );

if( debugging )
   alert( "Exits swapImage() with swapStatus=" + swapStatus );
By examining the content and order of the alert() as they appear, you can examine the health of your program very easily.

Use a JavaScript Debugger
A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution.

Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values.

The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both Mozilla and Netscape browsers can be downloaded at http://www.hacksrus.com/~ginda/venkman

Useful tips for developers
You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −

Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.

Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.

Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort.

Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.

Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.

Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.

Use descriptive variable and function names and avoid using single-character names.

Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).

Watch your equal signs. You should not used a single = for comparison purpose.

Declare variables explicitly using the var keyword.

For Loop JavaScript -library82.blogspot.com

The 'for' loop is the most compact form of looping. It includes the following three important parts −

The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.

The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.

The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.

Flow Chart
The flow chart of a for loop in JavaScript would be as follows −

For Loop
Syntax
The syntax of for loop is JavaScript is as follows −

for (initialization; test condition; iteration statement){
   Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.

<html>
   <body>
     
      <script type="text/javascript">
         <!--
            var count;
            document.write("Starting Loop" + "<br />");
       
            for(count = 0; count < 10; count++){
               document.write("Current Count : " + count );
               document.write("<br />");
            }
       
            document.write("Loop stopped!");
         //-->
      </script>
     
      <p>Set the variable to different value and then try...</p>
   </body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

JavaScript - Placement in HTML File library82.blogspot.com

There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −

Script in <head>...</head> section.

Script in <body>...</body> section.

Script in <body>...</body> and <head>...</head> sections.

Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can place JavaScript in an HTML file in different ways.

JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows −

<html>

   <head>
 
      <script type="text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
     
   </head>
 
   <body>
      <input type="button" onclick="sayHello()" value="Say Hello" />
   </body>
 
</html>
This code will produce the following results −


JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, you would not have any function defined using JavaScript. Take a look at the following code.

<html>

   <head>
   </head>
 
   <body>
 
      <script type="text/javascript">
         <!--
            document.write("Hello World")
         //-->
      </script>
     
      <p>This is web page body </p>
     
   </body>
</html>
This code will produce the following results −


JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as follows −

<html>
   <head>
      <script type="text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>
   </head>
 
   <body>
      <script type="text/javascript">
         <!--
            document.write("Hello World")
         //-->
      </script>
     
      <input type="button" onclick="sayHello()" value="Say Hello" />
     
   </body>
</html>
This code will produce the following result −


JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that there are cases where you are reusing identical JavaScript code on multiple pages of a site.

You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute.

<html>

   <head>
      <script type="text/javascript" src="filename.js" ></script>
   </head>
 
   <body>
      .......
   </body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension ".js" and then include that file as shown above.

For example, you can keep the following content in filename.js file and then you can use sayHello function in your HTML file after including the filename.js file.

function sayHello() {
   alert("Hello World")
}

Create employee table which have following structure.

Column No.
Column Type
Emp no
Varchar2
Emp name
Varchar2
hiredate
Date
Dept
Varchar2
Desig
Varchar2
Salary
Number
Hra
Number
Da
Number
Pf
Number
Tax
Number
Ma
Number
Net salary
Number

1.      Dept. should be MKT, ADM, SALES.
2.      Desig. Should be EXE, ACC, MGR, CLK.
3.      Calculate the hra as per the following condition.
a.   HRA                           CONDITION. (AS PER DESIG.)
6% of salary                MGR
4.5% of salary             EXE
3% of salary                ACC
1.5% of salary             CLK
4.      Calculate the da as per the following condition ( % of Basic).

Desig




Dept
MKT
49%
47%
45%
43%
ADM
47%
45%
43%
41%
SALES
45%
43%
41%
39%

5.      Calculate the pf as per the following condition.

PF                                CONDITION (AS PER DEPT)
3.5% of salary             MKT
2.5% of salary             ADM
1.5% of salary             SALES

6.      Calculate the tax as per the following condition.

CONDITION (AS PER SALARY)   Tax     MA

Salary > =10000                                  500      350
Salary >6000 & <10000                      400      250
Salary <6000                                       300      150

Net Salary = (salary+hra+da+ma)-(pf+tax)