0% found this document useful (0 votes)
2 views

javascript

The document provides an overview of JavaScript, highlighting its importance in web development as one of the three core technologies alongside HTML and CSS. It discusses JavaScript's features, applications, and limitations, emphasizing its versatility for both client-side and server-side development. Additionally, it covers JavaScript syntax, variables, operators, and control structures like if-else statements.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

javascript

The document provides an overview of JavaScript, highlighting its importance in web development as one of the three core technologies alongside HTML and CSS. It discusses JavaScript's features, applications, and limitations, emphasizing its versatility for both client-side and server-side development. Additionally, it covers JavaScript syntax, variables, operators, and control structures like if-else statements.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

WEB DESIGNING

(JAVA SCRIPT)
Faculty Name: Palak Shandil
Assistant Professor

Department of Computer Science and Engineering


Why Study JavaScript?
� JavaScript is one of the 3 languages all web developers must learn:
� 1. HTML to define the content of web pages
� 2. CSS to specify the layout of web pages
� 3. JavaScript to program the behavior of web pages
How JavaScript Makes HTML Build Website Better?
• JavaScript is an advanced programming language that makes web pages more interactive and
dynamic whereas HTML is a standard markup language that provides the primary structure of a
website.
• It simply adds dynamic content to websites to make them look good and HTML work on the look
of the website without the interactive effects and all.
• It manipulates the content to create dynamic web pages whereas HTML pages are static which
means the content cannot be changed.
• It is not cross-browser compatible whereas HTML is cross-browser compatible.
• It can be embedded inside HTML but HTML can not be embedded inside JavaScript.

Department of Computer Science and Engineering


� Things that Makes JavaScript Demanding
� JavaScript is the most popular and hence the most loved language around the globe.
Apart from this, there are abundant reasons to become the most demanding. Below are a
listing of a few important points:
• No need for compilers: Since JavaScript is an interpreted language, therefore it does not
need any compiler for compilation.
• Used both Client and Server Side: Earlier JavaScript was used to build client-side
applications only, but with the evolution of its frameworks namely Node.js and Express.js,
it is now widely used for building server-side applications too.
• Helps to build a complete solution: As we saw, JavaScript is widely used in both client
and server-side applications, therefore it helps us to build an end-to-end solution to a
given problem.
• Used everywhere: JavaScript is so loved because it can be used anywhere. It can be
used to develop websites, games or mobile apps, etc.
• Huge community support: JavaScript has a huge community of users and mentors who
love this language and take it’s legacy forward.
Department of Computer Science and Engineering
� What is JavaScript ?
� JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming
language. It is also known as the scripting language for webpages. It is well-known for the
development of web pages, and many non-browser environments also use it.
� JavaScript is a weakly typed language (dynamically typed). JavaScript can be used
for Client-side developments as well as Server-side developments. JavaScript is both an imperative
and declarative type of language. JavaScript contains a standard library of objects, like Array, Date,
and Math, and a core set of language elements like operators, control structures, and statements.

Department of Computer Science and Engineering


• Client-side: It supplies objects to control a browser and its Document Object Model (DOM). Like
if client-side extensions allow an application to place elements on an HTML form and respond to
user events such as mouse clicks, form input, and page navigation. Useful libraries for the client
side are AngularJS, ReactJS, VueJS, and so many others.
• Server-side: It supplies objects relevant to running JavaScript on a server. For if the server-side
extensions allow an application to communicate with a database, and provide continuity of
information from one invocation to another of the application, or perform file manipulations on a
server. The useful framework which is the most famous these days is node.js.
• Imperative language – In this type of language we are mostly concerned about how it is to be
done. It simply controls the flow of computation. The procedural programming approach, object,
oriented approach comes under this as async await we are thinking about what is to be done further
after the async call.
• Declarative programming – In this type of language we are concerned about how it is to be done,
basically here logical computation requires. Her main goal is to describe the desired result without
direct dictation on how to get it as the arrow function does.

Department of Computer Science and Engineering


� How to Link JavaScript File in HTML ?
� JavaScript can be added to HTML file in two ways:
• Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the
<script> tag. The <script> tag can either be placed inside the <head> or the <body> tag according
to the requirement.
• External JS: We can write JavaScript code in another files having an extension.js and then link this
file inside the <head> tag of the HTML file in which we want to add this code.
� Syntax:
<script>
// JavaScript Code
</script>

Department of Computer Science and Engineering


� Features of JavaScript
� According to a recent survey conducted by Stack Overflow, JavaScript is the most popular
language on earth.
With advances in browser technology and JavaScript having moved into the server with Node.js and
other frameworks, JavaScript is capable of so much more. Here are a few things that we can do with
JavaScript:
• JavaScript was created in the first place for DOM manipulation. Earlier websites were mostly static,
after JS was created dynamic Web sites were made.
• Functions in JS are objects. They may have properties and methods just like other objects. They can
be passed as arguments in other functions.
• Can handle date and time.
• Performs Form Validation although the forms are created using HTML.
• No compiler is needed.

Department of Computer Science and Engineering


� Applications of JavaScript
• Web Development: Adding interactivity and behavior to static sites JavaScript was invented to do this in 1995. By using
AngularJS that can be achieved so easily.
• Web Applications: With technology, browsers have improved to the extent that a language was required to create robust web
applications. When we explore a map in Google Maps then we only need to click and drag the mouse. All detailed view is just a
click away, and this is possible only because of JavaScript. It uses Application Programming Interfaces(APIs) that provide extra
power to the code. The Electron and React are helpful in this department.
• Server Applications: With the help of Node.js, JavaScript made its way from client to server and Node.js is the most powerful
on the server side.
• Games: Not only in websites, but JavaScript also helps in creating games for leisure. The combination of JavaScript and HTML
5 makes JavaScript popular in game development as well. It provides the EaseJS library which provides solutions for working
with rich graphics.
• Smartwatches: JavaScript is being used in all possible devices and applications. It provides a library PebbleJS which is used in
smartwatch applications. This framework works for applications that require the Internet for their functioning.
• Art: Artists and designers can create whatever they want using JavaScript to draw on HTML 5 canvas, and make the sound more
effective also can be used p5.js library.
• Machine Learning: This JavaScript ml5.js library can be used in web development by using machine learning.
• Mobile Applications: JavaScript can also be used to build an application for non-web contexts. The features and uses of
JavaScript make it a powerful tool for creating mobile applications. This is a Framework for building web and mobile apps using
JavaScript. Using React Native, we can build mobile applications for different operating systems. We do not require to write code
for different systems.

Department of Computer Science and Engineering


� Limitations of JavaScript
• Security risks: JavaScript can be used to fetch data using AJAX or by manipulating tags that load
data such as <img>, <object>, <script>. These attacks are called cross-site script attacks. They inject
JS that is not part of the site into the visitor’s browser thus fetching the details.
• Performance: JavaScript does not provide the same level of performance as offered by many
traditional languages as a complex program written in JavaScript would be comparatively slow. But
as JavaScript is used to perform simple tasks in a browser, so performance is not considered a big
restriction in its use.
• Complexity: To master a scripting language, programmers must have a thorough knowledge of all
the programming concepts, core language objects, and client and server-side objects otherwise it
would be difficult for them to write advanced scripts using JavaScript.
• Weak error handling and type checking facilities: It is a weakly typed language as there is no
need to specify the data type of the variable. So wrong type checking is not performed by compile.

Department of Computer Science and Engineering


� JavaScript Syntax
JavaScript Syntax is used to define the set of rules to construct a JavaScript code. You need to follow all
these so that you can work with JavaScript.
Syntax:
console.log("Basic Print method in JavaScript");
JavaScript syntax refers to the set of rules that determines how JavaScript programs are constructed:
// Variable declaration
let c, d, e;

// Assign value to the variable


c = 5;

// Computer value of variables


d = c;
e = c/d;

Department of Computer Science and Engineering


� JavaScript Variables
� A JavaScript variable is the simple name of the storage location where data is stored. There are two types of variables in
JavaScript which are listed below:
• Local variables: Declare a variable inside of a block or function.
• Global variables: Declare a variable outside function or with a window object.

Department of Computer Science and Engineering


� JavaScript Operators
� JavaScript operators are symbols that are used to compute the value or in other words, we can
perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute the value, and
Assignment operators ( =, +=, %= ) are used to assign the values to variables.

Department of Computer Science and Engineering


� JavaScript Expression
� Expression is the combination of values, operators, and variables. It is used to compute the values.

Department of Computer Science and Engineering


JavaScript Operators
� The Addition Operator + adds numbers:
� The Assignment Operator = assigns a value to a variable.

Department of Computer Science and Engineering


Department of Computer Science and Engineering
� Types of JavaScript Operators
� There are different types of JavaScript operators:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators

Department of Computer Science and Engineering


JavaScript Assignment Operators JavaScript Arithmetic Operators
Assignment operators assign values to JavaScript variables.
The Addition Assignment Operator (+=) adds a value to a variable.

Operator Example Same As Operator Description


= x=y x=y + Addition
- Subtraction
+= x += y x=x+y
* Multiplication
-= x -= y x=x-y
** Exponentiation (ES2016)
*= x *= y x=x*y
/ Division
/= x /= y x=x/y
% Modulus (Division Remainder)
%= x %= y x=x%y
++ Increment
**= x **= y x = x ** y
-- Decrement

Department of Computer Science and Engineering


� JavaScript Comparison Operators
JavaScript Logical Operators

Operat Description
or
== equal to
=== equal value and equal type Operator Description
!= not equal && logical and
!== not equal value or not equal
type || logical or
> greater than ! logical not
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Department of Computer Science and Engineering
� JavaScript Bitwise Operators
� Bit operators work on 32 bits numbers.
� Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10


^ XOR 5^1 0101 ^ 0001 0100 4

<< left shift 5 << 1 0101 << 1 1010 10

>> right shift 5 >> 1 0101 >> 1 0010 2

>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2


Department of Computer Science and Engineering
� JavaScript Data Types
� JavaScript has 8 Datatypes
� 1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
� The Object Datatype
The object data type can contain:
� 1. An object
2. An array
3. A date

Department of Computer Science and Engineering


� The Concept of Data Types
� In programming, data types is an important concept.
� To be able to operate on variables, it is important to know something about the type.
JavaScript Strings
� A string (or a text string) is a series of characters like "John Doe".
� Strings are written with quotes. You can use single or double quotes:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Strings are written with quotes. You can use single or double quotes:</p>
<p id="demo"></p>
<script>
let carName1 = "Volvo XC60";
let carName2 = 'Volvo XC60';
document.getElementById("demo").innerHTML =
carName1 + "<br>" +
carName2;
</script>
</body>
</html>
Department of Computer Science and Engineering
� JavaScript If-else
� The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.
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. }

Department of Computer Science and Engineering


<html>
<body>
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
</body>
</html>

Department of Computer Science and Engineering


� JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is
given below.
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. }

Department of Computer Science and Engineering


<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>

Department of Computer Science and Engineering


� JavaScript If...else if statement
� It evaluates the content only if expression is true from several expressions. The signature of JavaScript if
else if statement is given below.
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. }

Department of Computer Science and Engineering


<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
Department of Computer Science and Engineering
� 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.
� The signature of JavaScript switch statement is given below.
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. default:
10. code to be executed if above values are not matched;
11. }
Department of Computer Science and Engineering
Department of Computer Science and Engineering
� 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) JavaScript For loop
� The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of
iteration is known. The syntax of for loop is given below.
1. for (initialization; condition; increment)
2. {
3. code to be executed
4. }

Department of Computer Science and Engineering


� <!DOCTYPE html>
� <html>
� <body>
� <script>
� for (i=1; i<=5; i++)
� {
� document.write(i + "<br/>")
� }
� </script>
� </body>
� </html>

Department of Computer Science and Engineering


� 2) JavaScript while loop
� The JavaScript while loop iterates the elements for the infinite number of times. It should be used
if number of iteration is not known. The syntax of while loop is given below.
1. while (condition)
2. {
3. code to be executed
4. }

Department of Computer Science and Engineering


� <!DOCTYPE html>
� <html>
� <body>
� <script>
� var i=11;
� while (i<=15)
� {
� document.write(i + "<br/>");
� i++;
� }
� </script>
� </body>
� </html>

Department of Computer Science and Engineering


� 3) JavaScript do while loop
� The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do while
loop is given below.
1. do{
2. code to be executed
3. }while (condition);

Department of Computer Science and Engineering


� <!DOCTYPE html>
� <html>
� <body>
� <script>
� var i=21;
� do{
� document.write(i + "<br/>");
� i++;
� }while (i<=25);
� </script>
� </body>
� </html>

Department of Computer Science and Engineering


� JavaScript Functions
� JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse
the code.
� Advantage of JavaScript function
� There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
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.
� JavaScript Function Example
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>

Department of Computer Science and Engineering


� JavaScript Function Arguments
� We can call function by passing arguments. Let’s see the example of function that has one
argument.
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>

Department of Computer Science and Engineering


� Function with Return Value
� We can call function that returns a value and use it in our program. Let’s see the example of
function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>

Department of Computer Science and Engineering


� JavaScript Function Object
� In JavaScript, the purpose of Function constructor is to create a new Function object. It executes
the code globally. However, if we call the constructor directly, a function is created dynamically
but in an unsecured way.
� Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

� 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 an object-based language. Everything is an object in JavaScript.

Department of Computer Science and Engineering


� Creating Objects in JavaScript
� There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) JavaScript Object by object literal
� The syntax of creating object using object literal is given below:
1. object={property1:value1,property2:value2.....propertyN:valueN}
� As you can see, property and value is separated by : (colon).
� Let’s see the simple example of creating object in JavaScript.
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>

Department of Computer Science and Engineering


2) By creating instance of Object
� The syntax of creating object directly is given below:
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>

Department of Computer Science and Engineering


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. document.write(e.id+" "+e.name+" "+e.salary);
9. </script>

Department of Computer Science and Engineering


JavaScript Object Methods
� The various methods of Object are as follows:
S.No Methods Description

1 Object.assign() This method is used to copy enumerable and own properties from a source
object to a target object
2 Object.create() This method is used to create a new object with the specified prototype object
and properties.
3 Object.defineProperty() This method is used to describe some behavioral attributes of the property.
4 Object.defineProperties() This method is used to create or configure multiple object properties.
5 Object.entries() This method returns an array with arrays of the key, value pairs.
6 Object.freeze() This method prevents existing properties from being removed.
7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified property of the
specified object.
8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a given object.
9 Object.getOwnPropertyNames() This method returns an array of all properties (enumerable or not) found.
10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key properties.
11 Object.getPrototypeOf() This method returns the prototype of the specified object.
12 Object.is() This method determines whether two values are the same value.
13 Object.isExtensible() This method determines if an object is extensible
14 Object.isFrozen() This method determines if an object was frozen.
15 Object.isSealed() This method determines if an object is sealed.
16 Object.keys() This method returns an array of a given object's own property names.
17 Object.preventExtensions() This method is used to prevent any extensions of an object.
18 Object.seal() This method prevents new properties from being added and marks all existing
Department of Computer Science and Engineering
properties as non-configurable.
19 Object.setPrototypeOf() This method sets the prototype of a specified object to another object.
20 Object.values() This method returns an array of values.
� JavaScript Array
� JavaScript array is an object that represents a collection of similar type of elements.
� There are 3 ways to construct array in JavaScript
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
� The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
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>

Department of Computer Science and Engineering


2) JavaScript Array directly (new keyword)
� The syntax of creating array directly is given below:
var arrayname=new Array();
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7. for (i=0;i<emp.length;i++){
8. document.write(emp[i] + "<br>");
9. }
10. </script>

Department of Computer Science and Engineering


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.
� The example of creating object by array constructor is given below.
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>

Department of Computer Science and Engineering


� JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event Handlers.
� For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
Mouse Event:
Event Performed Event Handler Description
click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


Department of Computer Science and Engineering
Keyboard Event:

Event Performed Event Handler Description


Keydown & Keyup onkeydown & onkeyup When the user press and
then release the key

Form Event:

Event Performed Event Handler Description


focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form


element
change onchange When the user modifies or changes the
value of a form element
Department of Computer Science and Engineering
� Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>

Department of Computer Science and Engineering


� MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>

Department of Computer Science and Engineering


� Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>

Department of Computer Science and Engineering


� JavaScript Popup Boxes
1. Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
� <!DOCTYPE html>
� <html>
� <body>
� <h2>JavaScript Alert</h2>
� <button onclick="myFunction()">Try it</button>
� <script>
� function myFunction() {
� alert("I am an alert box!");
� }
� </script>
� </body>
� </html>

Department of Computer Science and Engineering


2. Confirm Box
� A confirm box is often used if you want the user to verify or accept something.
� When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
� If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
window.confirm("sometext");
� <!DOCTYPE html>
� <html>
� <body>
� <h2>JavaScript Confirm Box</h2>
� <button onclick="myFunction()">Try it</button>
� <p id="demo"></p>
� <script>
� function myFunction() {
� var txt;
� if (confirm("Press a button!")) {
� txt = "You pressed OK!";
� } else {
� txt = "You pressed Cancel!";
� }
� document.getElementById("demo").innerHTML = txt;
� }
� </script>
� </body> Department of Computer Science and Engineering
� </html>
3. Prompt Box
� A prompt box is often used if you want the user to input a value before entering a page.
� When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
� If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax:
window.prompt("sometext","defaultText");

� <!DOCTYPE html>

� <html>

� <body>

� <h2>JavaScript Prompt</h2>

� <button onclick="myFunction()">Try it</button>

� <p id="demo"></p>

� <script>

� function myFunction() {

� let text;

� let person = prompt("Please enter your name:", "Harry Potter");

� if (person == null || person == "") {

� text = "User cancelled the prompt.";

� } else {

� text = "Hello " + person + "! How are you today?";

� }

� document.getElementById("demo").innerHTML = text;

� }

� </script>

� </body>

� </html>
Department of Computer Science and Engineering
How to validate a form using Javascript
� <!DOCTYPE html>
� <html>
� <head>
� <script>
� function validateForm() {
� let x = document.forms["myForm"]["fname"].value;
� if (x == "") {
� alert("Name must be filled out");
� return false;
� }
� }
� </script>
� </head>
� <body>
� <h2>JavaScript Validation</h2>
� <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
� Name: <input type="text" name="fname">
� <input type="submit" value="Submit">
� </form>
� </body>
� </html>

Department of Computer Science and Engineering


� Data Validation
� Data validation is the process of ensuring that user input is clean, correct, and
useful.
� Typical validation tasks are:
• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?
� Most often, the purpose of data validation is to ensure correct user input.
� Validation can be defined by many different methods, and deployed in many
different ways.
� Server side validation is performed by a web server, after input has been sent to
the server.
� Client side validation is performed by a web browser, before input is sent to a
web server.

Department of Computer Science and Engineering


� HTML Constraint Validation
� HTML5 introduced a new HTML validation concept called constraint
validation.
� HTML constraint validation is based on:
• Constraint validation HTML Input Attributes
• Constraint validation CSS Pseudo Selectors
• Constraint validation DOM Properties and Methods

Department of Computer Science and Engineering


� Constraint Validation HTML Input Attributes
Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

� Constraint Validation CSS Pseudo Selectors


Selector Description

:disabled Selects input elements with the "disabled" attribute specified

:invalid Selects input elements with invalid values

:optional Selects input elements with no "required" attribute specified

:required Selects input elements with the "required" attribute specified

:valid Selects input elements with valid values

Department of Computer Science and Engineering

You might also like