Unit III JAVA SCRIPT
Unit III JAVA SCRIPT
Meenakshi Patel
What You Can Do with JavaScript
JavaScript code directly within your web pages by placing it between the <script> and
</script> tags.
The <script> tag indicates the browser that the contained statements are to be interpreted as
executable script and not HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inlining JavaScript</title>
</head>
<body>
</body>
</html>
Difference Between Client-side and Server-side Scripting
Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by
the web browser,
while server-side scripting languages such as PHP, ASP, Java, Python, Ruby, etc. runs on the web
server and the output sent back to the web browser in HTML format.
JavaScript Syntax
var x = 5;
var y = 10;
var sum = x + y;
console.log(myVar);
console.log(MyVar);
console.log(myvar);
JavaScript Comments
document.write("Hello World!");
in JavaScript */
document.write("Hello World!");
JavaScript Variables
Variables are used to store data, like string of text, numbers, etc.
The data or value stored in the variables can be set, updated, and retrieved whenever needed.
// Declaring Variable
var userName;
// Assigning value
age = 21,
isMarried = false;
The let and const Keywords
The const keyword works exactly the same as let, except that variables declared using const keyword cannot
be reassigned later in the code.
// Declaring variables
// Declaring constant
const PI = 3.14;
console.log(PI); // 3.14
// Trying to reassign
PI = 10; // error
Unlike var, which declare function-scoped variables,
both let and const keywords declare variables, scoped at block-level ({}).
Block scoping means that a new scope is created between a pair of curly brackets {}.
Naming Conventions for JavaScript Variables
● A variable name must start with a letter, underscore (_), or dollar sign ($).
● A variable name cannot start with a number.
● A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscores.
● A variable name cannot contain spaces.
● A variable name cannot be a JavaScript keyword or a JavaScript reserved word.
JavaScript Reserved Keywords
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>
Declaring JavaScript global variable within function
To declare JavaScript global variables inside function, you need to use window object. For example:
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. }
Internals of global variable in JavaScript
When you declare a variable outside the function, it is added in the window object internally. You can access it through
window object also. For example:
1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }
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.
Creating Objects in JavaScript
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
4.
1) JavaScript Object 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>
2) By creating instance of 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>
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.
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>
JavaScript Array
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript 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>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
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>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value
explicitly.
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>
JavaScript String
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given below:
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
2) By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>
JavaScript Date Object
The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of
JavaScript date object.
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)
JavaScript Date Example
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
1. <script>
2. var x=0;
3. var y=1;
4. var z=-1;
5. document.writeln(Number.isFinite(x));
6. document.writeln(Number.isFinite(y));
7. document.writeln(Number.isFinite(z));
8. </script>
Browser Object Model
The Browser Object Model (BOM) is used to interact with the browser.
1. window.alert("hello javatpoint");
is same as:
1. alert("hello javatpoint");
Window Object
The window object represents a window in browser. An object of window is created automatically by the browser.
Methods of window object
Example of alert() in javascript
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
Example of confirm() in javascript
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()"/>
Example of prompt() in javascript
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()"/>
Example of open() in javascript
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.google.com");
4. }
5. </script>
6. <input type="button" value="google" onclick="msg()"/>
Example of setTimeout() in javascript
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()"/>
JavaScript History Object
The JavaScript history object represents an array of URLs visited by the user. By using this object, you can load previous,
forward or any particular page.
1. window.history
Or,
1. history
Example of history object
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
Property of JavaScript navigator object
Methods of JavaScript navigator object
Example of navigator object
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>
JavaScript Screen Object
The JavaScript screen object holds information of browser screen. It can be used to display screen width, height,
colorDepth, pixelDepth etc.
1. window.screen
Or,
1. screen
Property of JavaScript Screen Object
Example of JavaScript Screen Object
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>
Document Object Model
By the help of document object, we can add dynamic content to our web page.
1. window.document
Is same as
1. document
Properties of document object
Methods of document object
Accessing field value by document object
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
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. <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>
Javascript - document.getElementsByName() method
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>
Javascript - document.getElementsByTagName() method
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 getElementByTagName() method.</p>
10. <p>Let's see the simple example</p>
11. <button onclick="countpara()">count paragraph</button>
Javascript - innerHTML
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.
Example of innerHTML 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.
Javascript innerText Example
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>
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have inappropriate values. So, validation is must to
authenticate user.
JavaScript Form Validation Example
1. <script> 1. </script>
2. function validateform(){ 2. <body>
3. var name=document.myform.name.value; 3. <form name="myform" method="post"
4. var action="abc.jsp" onsubmit="return
password=document.myform.password.val validateform()" >
ue; 4. Name: <input type="text"
5. name="name"><br/>
6. if (name==null || name==""){ 5. Password: <input type="password"
7. alert("Name can't be blank"); name="password"><br/>
8. return false; 6. <input type="submit" value="register">
9. }else if(password.length<6){ 7. </form>
10. alert("Password must be at least 6
characters long.");
11. return false;
12. }
13. }
JavaScript Retype Password Validation
1. <script type="text/javascript"> 1. }
2. function matchpass(){ 2. }
3. var 3. </script>
firstpassword=document.f1.password.value 4.
; 5. <form name="f1" action="register.jsp"
4. var onsubmit="return matchpass()">
secondpassword=document.f1.password2. 6. Password:<input type="password"
value; name="password" /><br/>
5. 7. Re-enter Password:<input type="password"
6. if(firstpassword==secondpassword){ name="password2"/><br/>
7. return true; 8. <input type="submit">
8. } 9. </form>
9. else{
10. alert("password must be same!");
11. return false;
JavaScript Number Validation
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>
JavaScript validation with image
1. <script> 1. status=true;
2. function validate(){ 2. }
3. var name=document.f1.name.value;
4. var 1. if(password.length<6){
password=document.f1.password.value; 2. document.getElementById("passwordloc").i
8. document.getElementById("nameloc").inner 4. status=false;
HTML= 5. }else{
10. status=false; 7. }
12. document.getElementById("nameloc").inner
HTML=" <img src='checked.gif'/>";
1. }
2. </script>
3.
4. <form name="f1" action="#"
onsubmit="return validate()">
5. <table>
6. <tr><td>Enter Name:</td><td><input
type="text" name="name"/>
7. <span id="nameloc"></span></td></tr>
8. <tr><td>Enter Password:</td><td><input
type="password" name="password"/>
9. <span id="passwordloc"></span></td></tr>
10. <tr><td colspan="2"><input type="submit"
value="register"/></td></tr>
11. </table>
12. </form>
JavaScript email validation
There are many criteria that need to be follow to validate the email id such as: