Javascript Tutorial: Where Javascript Is Used
Javascript Tutorial: Where Javascript Is Used
Javascript Tutorial: Where Javascript Is Used
o Client-side validation
o Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog
box and prompt dialog box)
o Displaying clocks etc.
JavaScript Example
1. <h2>Welcome to JavaScript</h2>
2. <script>
3. document.write("Hello JavaScript by JavaScript");
4. </script>
Test it Now
Prerequisite
Before learning JavaScript, you must have the basic knowledge of HTML.
Audience
We have developed this JavaScript tutorial for beginners and professionals. There are
given a lot of examples with JavaScript editor. You will get point to point explanation of
each JavaScript topics. Our tutorial will help beginners and professionals to learn
JavaScript easily.
Problem
If there is any problem related to JavaScript, you can post your question in forum. We
will definitely sort out your problems
JavaScript Example
1. JavaScript Example
2. Within body tag
3. Within head tag
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript
code: within body tag, within head tag and external JavaScript file.
1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>
Test it Now
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about
the data.
1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
Test it Now
In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call
msg() function.
1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");
6. }
7. </script>
8. </head>
9. <body>
10. <p>Welcome to JavaScript</p>
11. <form>
12. <input type="button" value="click" onclick="msg()"/>
13. </form>
14. </body>
15. </html>
Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
1. function msg(){
2. alert("Hello Javatpoint");
3. }
Let’s include the JavaScript file into html page. It calls the JavaScript function on button
click.
index.html
1. <html>
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10. </body>
11. </html>
JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.
1. To make code easy to understand It can be used to elaborate the code so that
end user can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be need to disable the code. In such case, it is better to use
comments.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.
Let’s see the example of single-line comment i.e. added before the statement.
1. <script>
2. // It is single line comment
3. document.write("hello javascript");
4. </script>
Test it Now
Let’s see the example of single-line comment i.e. added after the statement.
1. <script>
2. var a=10;
3. var b=20;
4. var c=a+b;//It adds values of a and b variable
5. document.write(c);//prints sum of 10 and 20
6. </script>
Test it Now
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
1. /* your code here */
1. <script>
2. /* It is multi line comment.
3. It will not be displayed */
4. document.write("example of javascript multiline comment");
5. </script>
JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable
A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
2. var *aa=320;
1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
Test it Now
Output of the above example
30
1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>
Or,
1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>
1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10. b();
11. </script>
JavaScript Global Variable
A JavaScript global variable is declared outside the function or declared with window
object. It can be accessed from any function.
1. <script>
2. var value=50;//global variable
3. function a(){
4. alert(value);
5. }
6. function b(){
7. alert(value);
8. }
9. </script>
Test it Now
1. window.value=90;
Now it can be declared inside any function and can be accessed from any function. For
example:
1. function m(){
2. window.value=100;//declaring global variable by window object
3. }
4. function n(){
5. alert(window.value);//accessing global variable from other function
6. }
Test it Now
1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
1. var a=40;//holding number
2. var b="Rahul";//holding string
Data Description
Type
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For
example:
1. var sum=10+20;
1. Arithmetic Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
1. if(expression){
2. //content to be evaluated
3. }
Flowchart of JavaScript If statement
1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
Test it Now
1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.
1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </script>
Test it Now
1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }
1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10. document.write("a is equal to 20");
11. }
12. else{
13. document.write("a is not equal to 10, 15 or 20");
14. }
15. </script>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page. But it
is convenient than if..else..if because it can be used with numbers, characters etc.
1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. break;
8. ......
9.
10. default:
11. code to be executed if above values are not matched;
12. }
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
9. result="B Grade";
10. break;
11. case 'C':
12. result="C Grade";
13. break;
14. default:
15. result="No Grade";
16. }
17. document.write(result);
18. </script>
Test it Now
The switch statement is fall-through i.e. all the cases will be evaluated if you don't use
break statement.
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result+=" A Grade";
7. case 'B':
8. result+=" B Grade";
9. case 'C':
10. result+=" C Grade";
11. default:
12. result+=" No Grade";
13. }
14. document.write(result);
15. </script>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1. for (initialization; condition; increment)
2. {
3. code to be executed
4. }
1. <script>
2. for (i=1; i<=5; i++)
3. {
4. document.write(i + "<br/>")
5. }
6. </script>
Test it Now
Output:
1
2
3
4
5
1. while (condition)
2. {
3. code to be executed
4. }
1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </script>
Test it Now
Output:
11
12
13
14
15
1. do{
2. code to be executed
3. }while (condition);
1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>
Test it Now
Output:
21
22
23
24
25
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.
2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.
1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Test it Now
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Test it Now
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
1. By object literal
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
Test it Now
1. var objectname=new Object();
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Test it Now
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>
Test it Now
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Test it Now
1. By array literal
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let’s see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Test it Now
1. var arrayname=new Array();
Here, new keyword is used to create instance of array.
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Test it Now
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now
1. By string literal
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
1. var stringname="string value";
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
Test it Now
Output:
1. var stringname=new String("string literal");
Output:
o charAt(index)
o concat(str)
o indexOf(str)
o lastIndexOf(str)
o toLowerCase()
o toUpperCase()
o slice(beginIndex, endIndex)
o trim()
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Test it Now
Output:
v
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Test it Now
Output:
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Test it Now
Output:
11
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>
Test it Now
Output:
16
5) JavaScript String toLowerCase() Method
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Test it Now
Output:
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>
Test it Now
Output:
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Test it Now
Output:
cde
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Test it Now
Output:
javascript trim
You can use different Date constructors to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.
Constructor
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Method Description
getFullYear() returns the year in 4 digit e.g. 2015. It is a new method and
suggested than getYear() which is now deprecated.
getHours() returns all the elements having the given name value.
getMinutes() returns all the elements having the given class name.
getSeconds() returns all the elements having the given class name.
getMilliseconds( returns all the elements having the given tag name.
)
1. Current Date and Time: <span id="txt"></span>
2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>
Test it Now
Output:
Current Date and Time: Sat Jan 27 2018 14:56:23 GMT+0530 (India Standard Time)
1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>
Output:
1. Current Time: <span id="txt"></span>
2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>
Test it Now
Output:
Current Time: 14:56:23
1. Current Time: <span id="txt"></span>
2. <script>
3. window.onload=function(){getTime();}
4. function getTime(){
5. var today=new Date();
6. var h=today.getHours();
7. var m=today.getMinutes();
8. var s=today.getSeconds();
9. // add a zero in front of numbers<10
10. m=checkTime(m);
11. s=checkTime(s);
12. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
13. setTimeout(function(){getTime()},1000);
14. }
15. //setInterval("getTime()",1000);//another way
16. function checkTime(i){
17. if (i<10){
18. i="0" + i;
19. }
20. return i;
21. }
22. </script>
Test it Now
Output:
Current Time: 14:57:08
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
1. Square Root of 17 is: <span id="p1"></span>
2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>
Test it Now
Output:
Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.
1. Random Number is: <span id="p2"></span>
2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>
Test it Now
Output:
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
1. 3 to the power of 4 is: <span id="p3"></span>
2. <script>
3. document.getElementById('p3').innerHTML=Math.pow(3,4);
4. </script>
Test it Now
Output:
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.
1. Floor of 4.6 is: <span id="p4"></span>
2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);
4. </script>
Test it Now
Output:
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For
example 4 for 3.7, 6 for 5.9 etc.
1. Ceil of 4.6 is: <span id="p5"></span>
2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>
Test it Now
Output:
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the given
number. If fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise
lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
1. Round of 4.3 is: <span id="p6"></span><br>
2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>
Test it Now
Output:
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc.
1. Absolute value of -4 is: <span id="p8"></span>
2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>
Test it Now
Output:
By the help of Number() constructor, you can create number object in JavaScript. For
example:
1. var n=new Number(value);
1. var x=102;//integer value
2. var y=102.7;//floating point value
3. var z=13e4;//exponent value, output: 130000
4. var n=new Number(16);//integer value by number object
Test it Now
Output:
Constant Description
Methods Description
JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.
1. Boolean b=new Boolean(value);
Property Description
constructo returns the reference of Boolean function that created Boolean object.
r
prototype enables you to add properties and methods in Boolean prototype.
Method Description
The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:
1. window.alert("hello javatpoint");
is same as:
1. alert("hello javatpoint");
You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,
Note: The document object represents an html document. It forms DOM (Document Object
Model).
Visit the next page to learn about window object fully with example.
Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Note: if html document contains frame or iframe, browser creates additional window
objects for each frame.
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and
cancel button.
setTimeout( performs action after specified time like calling function, evaluating
) expressions etc.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
Or,
1. history
No Method Description
.
The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.
1. window.navigator
Or,
1. navigator
No Method Description
.
1. <script>
2. document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
3. document.writeln("<br/>navigator.appName: "+navigator.appName);
4. document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
5. document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
6. document.writeln("<br/>navigator.language: "+navigator.language);
7. document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
8. document.writeln("<br/>navigator.platform: "+navigator.platform);
9. document.writeln("<br/>navigator.onLine: "+navigator.onLine);
10. </script>
Test it Now
navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
navigator.platform: Win32
navigator.onLine: true
1. window.screen
Or,
1. screen
1. <script>
2. document.writeln("<br/>screen.width: "+screen.width);
3. document.writeln("<br/>screen.height: "+screen.height);
4. document.writeln("<br/>screen.availWidth: "+screen.availWidth);
5. document.writeln("<br/>screen.availHeight: "+screen.availHeight);
6. document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
7. document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
8. </script>
Test it Now
screen.width: 1366
screen.height: 768
screen.availWidth: 1366
screen.availHeight: 728
screen.colorDepth: 24
screen.pixelDepth: 24
1. window.document
Is same as
1. document
According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName( returns all the elements having the given class name.
)
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome
message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>
Javascript -document.getElementById()
method
1. getElementById() method
2. Example of getElementById()
Let's see the simple example of document.getElementById() method that prints cube of
the given number.
1. <script type="text/javascript">
2. function getcube(){
3. var number=document.getElementById("number").value;
4. alert(number*number*number);
5. }
6. </script>
7. <form>
8. Enter No:<input type="text" id="number" name="number"/><br/>
9. <input type="button" value="cube" onclick="getcube()"/>
10. </form>
Enter No:
Javascript - document.getElementsByName()
method
1. getElementsByName() method
2. Example of getElementsByName()
1. document.getElementsByName("name")
1. <script type="text/javascript">
2. function totalelements()
3. {
4. var allgenders=document.getElementsByName("gender");
5. alert("Total Genders:"+allgenders.length);
6. }
7. </script>
8. <form>
9. Male:<input type="radio" name="gender" value="male">
10. Female:<input type="radio" name="gender" value="female">
11.
12. <input type="button" onclick="totalelements()" value="Total Genders">
13. </form>
Male: Female:
Javascript -
document.getElementsByTagName() method
1. getElementsByTagName() method
2. Example of getElementsByTagName()
The document.getElementsByTagName() method returns all the element of specified
tag name.
1. document.getElementsByTagName("name")
1. <script type="text/javascript">
2. function countpara(){
3. var totalpara=document.getElementsByTagName("p");
4. alert("total p tags are: "+totalpara.length);
5.
6. }
7. </script>
8. <p>This is a pragraph</p>
9. <p>Here we are going to count total number of paragraphs by getElementByTag
Name() method.</p>
10. <p>Let's see the simple example</p>
11. <button onclick="countpara()">count paragraph</button>
count paragraph
Another example of
document.getElementsByTagName() method
In this example, we going to count total number of h2 and h3 tags used in the
document.
1. <script type="text/javascript">
2. function counth2(){
3. var totalh2=document.getElementsByTagName("h2");
4. alert("total h2 tags are: "+totalh2.length);
5. }
6. function counth3(){
7. var totalh3=document.getElementsByTagName("h3");
8. alert("total h3 tags are: "+totalh3.length);
9. }
10. </script>
11. <h2>This is h2 tag</h2>
12. <h2>This is h2 tag</h2>
13. <h3>This is h3 tag</h3>
14. <h3>This is h3 tag</h3>
15. <h3>This is h3 tag</h3>
16. <button onclick="counth2()">count h2</button>
17. <button onclick="counth3()">count h3</button>
This is h2 tag
This is h2 tag
This is h3 tag
This is h3 tag
This is h3 tag
count h2 count h3
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration
form, comment form, links etc.
In this example, we are dynamically writing the html form inside the div name having
the id mylocation. We are identifing this position by calling the
document.getElementById() method.
1. <script type="text/javascript" >
2. function showcommentform() {
3. var data="Name:<input type='text' name='name'><br>Comment:<br><text
area rows='5' cols='80'></textarea>
4. <br><input type='submit' value='Post Comment'>";
5. document.getElementById('mylocation').innerHTML=data;
6. }
7. </script>
8. <form name="myForm">
9. <input type="button" value="comment" onclick="showcommentform()">
10. <div id="mylocation"></div>
11. </form>
Test it Now
Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html document.
Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.
1. <script type="text/javascript" >
2. function validate() {
3. var msg;
4. if(document.myForm.userPass.value.length>5){
5. msg="good";
6. }
7. else{
8. msg="poor";
9. }
10. document.getElementById('mylocation').innerText=msg;
11. }
12.
13. </script>
14. <form name="myForm">
15. <input type="password" value="" name="userPass" onkeyup="validate()">
16. Strength:<span id="mylocation">no strength</span>
17. </form>
Test it Now
Strength:no strength
It is important to validate the form submitted by the user because it can have
inappropriate values. So validation is must.
The JavaScript provides you the facility the validate the form on the client side so
processing will be fast than server-side validation. So, most of the web developers prefer
JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile number etc
fields.
Here, we are validating the form on form submit. The user will not be forwarded to the
next page until given values are correct.
1. <script>
2. function validateform(){
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5.
6. if (name==null || name==""){
7. alert("Name can't be blank");
8. return false;
9. }else if(password.length<6){
10. alert("Password must be at least 6 characters long.");
11. return false;
12. }
13. }
14. </script>
15. <body>
16. <form name="myform" method="post" action="abc.jsp" onsubmit="return valid
ateform()" >
17. Name: <input type="text" name="name"><br/>
18. Password: <input type="password" name="password"><br/>
19. <input type="submit" value="register">
20. </form>
Test it Now
1. <script>
2. function validate(){
3. var num=document.myform.num.value;
4. if (isNaN(num)){
5. document.getElementById("numloc").innerHTML="Enter Numeric value only";
6. return false;
7. }else{
8. return true;
9. }
10. }
11. </script>
12. <form name="myform" onsubmit="return validate()" >
13. Number: <input type="text" name="num"><span id="numloc"></span><br
/>
14. <input type="submit" value="submit">
15. </form>
Test it Now
JavaScript validation with image
Let’s see an interactive JavaScript form validation example that displays correct and
incorrect image if input is correct or incorrect.
1. <script>
2. function validate(){
3. var name=document.f1.name.value;
4. var password=document.f1.password.value;
5. var status=false;
6.
7. if(name.length<1){
8. document.getElementById("nameloc").innerHTML=
9. " <img src='unchecked.gif'/> Please enter your name";
10. status=false;
11. }else{
12. document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
13. status=true;
14. }
15. if(password.length<6){
16. document.getElementById("passwordloc").innerHTML=
17. " <img src='unchecked.gif'/> Password must be at least 6 char long";
18. status=false;
19. }else{
20. document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>
";
21. }
22. return status;
23. }
24. </script>
25.
26. <form name="f1" action="#" onsubmit="return validate()">
27. <table>
28. <tr><td>Enter Name:</td><td><input type="text" name="name"/>
29. <span id="nameloc"></span></td></tr>
30. <tr><td>Enter Password:</td><td><input type="password" name="passwo
rd"/>
31. <span id="passwordloc"></span></td></tr>
32. <tr><td colspan="2"><input type="submit" value="register"/></td></tr>
33. </table>
34. </form>
Test it Now
Output:
Enter Name:
Enter Password:
register
There are many criteria that need to be follow to validate the email id such as:
1. <script>
2. function validateemail()
3. {
4. var x=document.myform.email.value;
5. var atposition=x.indexOf("@");
6. var dotposition=x.lastIndexOf(".");
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
8. alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposit
ion:"+dotposition);
9. return false;
10. }
11. }
12. </script>
13. <body>
14. <form name="myform" method="post" action="#" onsubmit="return validatee
mail();">
15. Email: <input type="text" name="email"><br/>
16.
17. <input type="submit" value="register">
18. </form>
Events Description
onfocus occurs when an element gets focus such as button, input, textarea
etc.
onmouseout occurs when mouse is moved out from an element (after moved
over).
1) What is JavaScript?
JavaScript is a scripting language. It is different from Java language. It is object-based,
lightweight and cross platform. It is widely used for client side validation. More details...
1. <script type="text/javascript">
2. document.write("JavaScript Hello World!");
3. </script>
More details...
1. <script type="text/javascript" src="message.js"></script>
More details...
5) Is JavaScript case sensitive language?
Yes.
6) What is BOM?
BOM stands for Browser Object Model. It provides interaction with the browser. The
default object of browser is window.
It is used to display the popup dialog box such as alert dialog box, confirm dialog box,
input dialog box etc.
More details...
1. history.back()
2. history.forward()
More details...
10) How to write comment in JavaScript?
There are two types of comments in JavaScript.
More details...
1. function function_name(){
2. //function body
3. }
More details...
More details...
1. document.getElementById('mylocation').innerHTML="<h2>This is heading using
JavaScript</h2>";
More details...
15) How to write normal text code using JavaScript
dynamically?
The innerText property is used to write the simple text using JavaScript dynamically.
Let's see a simple example:
1. document.getElementById('mylocation').innerText="This is text using JavaScript"
;
More details...
1. By object literal
3. By Object Constructor
1. emp={id:102,name:"Rahul Kumar",salary:50000}
More details...
1. By array literal
1. var emp=["Shyam","Vimal","Ratan"];
More details...
Server side JavaScript also resembles like client side java script. It has relevant java
script which is to run in a server. The server side JavaScript are deployed only after
compilation.
The Netscape navigator on Windows uses cookies.txt file that contains all the cookies.
The path is : c:\Program Files\Netscape\Users\username\cookies.txt
The Internet Explorer stores the cookies on a file username@website.txt. The path is:
c:\Windows\Cookies\username@Website.txt.
1. int number;//Here, number has undefined value.
Null value: A value that is explicitly specified by the keyword "null" is known as null
value. For example:
1. String str=null;//Here, str has a null value.
1. <script>
2. window.document.body.style.cursor = "wait";
3. </script>
o Confirm Box
o Prompt Box
1. <form name="myform" action="index.php">
2. Search: <input type='text' name='query' />
3. <a href="javascript: submitform()">Search</a>
4. </form>
5. <script type="text/javascript">
6. function submitform()
7. {
8. document.myform.submit();
9. }
10. </script>