Introduction To Javascript
Introduction To Javascript
Javascript
Introduction to JavaScript
JavaScript is a scripting language that is used in most of the modern HTML pages. It gives a dynamic touch to
them.
JavaScript is used to change the content of HTML elements dynamically. It can also be used to read the
content of HTML elements and validate them and eventually show corresponding message to the user.
Just like we have tags for HTML elements, JavaScript is written inside <script></script> tags. By convention
script tags are placed inside head tag, although it is not necessary to do that.
Below is a sample of JavaScript code, an alert method to display messages as pop-up .
OUTPUT
When the browser loads the web page, the scripts are also loaded. Thus in an above example, as soon as the
web page is loaded the browser ran the script and the alert method was executed.
The JavaScript can be included in the web page in two ways.
We can either write the code in script tag or write the code in another external file, save it with .js extension.
For example we can write “alert('hello');” in a text file and save it as myfile.js
Then we can include the js file in the web page using src attribute of <script> tag.
<script src=”myfile.js”></script>
Variables
Variables are used to store data and manipulate it, just like we had in any programming language.
A variable in JavaScript is declared as:
var variableName=data;
To declare a variable, “var” keyword is used. The data type of the variables is determined by the type of data
they hold.
Example:
var x=”George”; //string
x='a'; //char
x=5; //int
x=4.5 //float
x=true; //boolean
x=new Array(2,4,6,3); //array of integer
OUTPUT
Here we can see that same variable was able to store different values at different times. So java script
is type independent.
Events
An event is defined as an action performed over an HTML element. On various actions performed by
mouse or keyboard JavaScript code can be called.
We will discuss about four basic events. onclick, onsubmit, onchange, onselect
onclick event occurs when we click on any HTML element. Here is the sample code.
OUTPUT
When we click on a button, onclick event occurrs and the alert method is called as per the code.
onsubmit event occurs when the form is being submitted. Here is a sample code.\
OUTPUT
onchange event occurs whenever there is a change in the content of the particular element. For example:
OUTPUT
OUTPUT
When the text in the text box is selected onselect event occurs and according to the code the alert method
was called.
Functions
All java script codes written inside script tag gets executed after the page is loaded by the browser. If we want
to execute specific functionality on various events we should put the JavaScript codes inside the function and
call those function at the occurrence of event.
To write a function , the key word “function” is used, followed by the function name and the arguments.
funciton myFunction(argument1, argument2....){
var value=10;
return value;
}
A variable declared inside a function becomes a local variable and thus can be used within the function only. A
variable declared outside a function becomes a global variable and thus can be accessed by any function.
Sample Code:
OUTPUT
In the above example, logic for calculating area of a circle is placed. On the event of clicking on the button
“Find Area” as shown, the function ‘calculateArea’ called and number 5 passed as an argument. The area of
the circle output is shown in an alert box.
A function can call another function and return value to the calling function. Here is an example.
OUTPUT
In this example add function was called by the calculate function and it returned the sum the numbers.
Conditional Operations
To compare between two expressions we need conditional operations. JavaScript support conditional
operations like if, if-else, if and nested else if.
Below is an example of if-else if :
OUTPUT
Here two numbers are compared and it is determined which number is greater.
For Loop
In JavaScript there are many ways to iterate, one of them is to use a for loop.
Sample Code:
OUTPUT
Here we iterated through the array of integers and calculated the sum of numbers. The result is shown in an
alert message.
This can also be achieved by placing the code inside a function and then calling the function through an event
on HTML element.
PopUp Box
In JavaScript we can create small pop-up windows to either show message or get input from user. JavaScript
provides three type of popup boxes:
Alert Box, Confirm Box and Prompt Box.
You have already seen alert box functionality, it is used to show messages as pop up.
Confirm box, as the name suggests, is used for confirmations. It returns either true or false when we click on
Ok and Cancel respectively.
Syntax: Event=”return confirm(Message)”;
when we write return, the boolean value returned will determine whether the form is submitted or not.
Sample Code:
OUTPUT
When you click on “Cancel”, false will be returned and the form will not be submitted.
When you click on “OK”, true will be returned and the form will proceed with the submission.
Prompt Box is used when we want an input from the user through the popup box.
Syntax: prompt(Message,default value);
The default value is not necessary to give and can be skipped. The return type is string that we enter in the
box.
Sample code:
OUTPUT
In the code we used inbuilt function parseInt() to convert string into int.
When a browser loads a web page, it creates the Document Object Model of the page.
It is a tree of HTML elements and we use it to traverse to various elements of the HTML page.
In the JavaScript function we can access the elements of the page either by traversing through the elements or
by using some of the methods of these objects.
getElementById:
This method is used to access an element using the unique id we assign to it while creating the page.
Sample Code:
OUTPUT
In the above example var x=document.getElementById("name") is used to access the text field having
id=name.
Here the document object's method getElementById is used.
The same could be achieved by writing
var x=document.forms["myForm"]["name"].value where we use the 2D form of document model.
or
var x=document.myForm.firstName.value where we cascade through elements using their names.
getElementsByName:
This method is used to get all the elements with the given name.
Sample code:
OUTPUT
Here all the elements by that name are stored as array of elements in variable x. After that we can we can
iterate through x and get all the elements and their value.
getElementsByTagName:
This method is used to get all the elements with the name of the tag.
Sample code:
OUTPUT
Here all the elements by the Tag name “input” are stored as array of elements in variable x. After that we can
we can iterate through x and get all the elements and check whether they are checked or not.\
Validations
We can use JavaScript to validate the data entered by the users. For instance, we can check whether user has
entered into the text field or not, whether user has enter a string in a number field, whether user has exceeded
the word limit etc.
In the example below we will be validating a form based on the criteria mentioned above.
OUTPUT
Here first validations were did to find out whether the fields were left blank or not.
To check whether a radio button or check box is checked or not, simply first get the element by name, id or tag
name and write the following conditional code:
if(x.checked), where x is the radio element or check box element. Thus we can validate each HTML element
using JavaScript.
Sample code:
OUTPUT
The above sample code that checks whether a radio button is checked or not.
As soon as JavaScript finds that the radio button is selected, it return true and the form proceeds with
submission. Otherwise false is returned and the form is not submitted. A corresponding message is also shown
through the alert box.
OUTPUT
In an above example, the select element fetched through the document object. Then index of the selected
option is checked. The index starts from 0. After clicking the submit button, if the index of selected option
remains the same, then that would mean the user did not select any option.
If the selected index is not 0 then the code would show the value of selected option in an alert box. i.e “x.value”
here would give the selected option value.
Javascript:
http://www.w3schools.com/js/DEFAULT.asp
Related Videos: