Introduction to JavaScript Basics
Introduction to JavaScript Basics
Java Script
JavaScript is an object-based client-side scripting language that is very popular and used to create
dynamic and interactive web pages. Javascript is an interpreted language usually used with HTML,
and programs written in JavaScript are called lightweight scripts.
Earlier, JavaScript was named LiveScript, but later, Netscape changed its name to JavaScript because
its origin was from Java which was very popular at that time. JavaScript released its first look
for Netscape 2.0 in 1995 under the name "LiveScript".
JavaScript can interact with HTML DOM elements and dynamically control the webpage.
You can perform client-side validation using Javascript.
Using JavaScript, you can create drop-down menus, pop-up windows, and dialog boxes.
JavaScript can be used to load asynchronous data without refreshing the webpage.
JavaScript can be used in game development.
Advantages of JavaScript
Speed: JavaScript is a client-side scripting language. It is very fast because all its code
functions run immediately on the client machine instead of contacting the server and waiting
for a response.
Simplicity: JavaScript is relatively easy to learn and code.
Versatility: JavaScript works well with other languages and is also used in various
applications.
Server Load: Being on the client-side reduces the requirement on the website server.
A script is a set of instructions given in the form of code. Instructions are designed for either the web
browser (client-side scripting) or the server (server-side scripting). Scripts provide changes to the web
page.
3.2 Internal and External Java Script
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used
to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and
</script> tags is called a script blog.
‘type’ attribute was the most important attribute of <script> tag. However, it is no longer used.
Browser understands that <script> tag has JavaScript code inside it.
<script></script>
Internal javaScript
Create an html file(.htm) extension and write javascript code inside the ‘script’ tag
then simply load the HTML file in the browser
External javaScript
Create a separate javascript file(.js) with .js extension. Write your code in it.
Now link this js file with the HTML document using script tag like:
<script src='relative_path_to_file/file_name.js'></script>
either in the body or in the head.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
</head>
<body>
<script>
</script>
</body>
</html>
We can put the script tag inside the ‘head’ or ‘body’ tag. Though it should be noted that each
choice of putting the ‘script’ tag has its own consequences. For now, you can put the script tag
anywhere you want.
Printing Hello World
In order to print the famous ‘Hello World’ sentence to the screen, we can make use of different
methods that javascript provides. Most common are:
[Link]()
[Link]()
alert()
Each of the above method have different ways of outputting the content. Though
‘[Link]()’ is used when we want to print the content onto the document which is the
HTML Document. Also ‘[Link]()’ is mainly used when we are debugging javascript code
and same thing with ‘alert()’.
Example:
<script>
// using [Link]
[Link]('Hello World');
</script>
Hit Ctrl+Shift+J to see the output in the browser console. Or press f12 key.
[Link]
<script>
// using [Link]
[Link]('Hello World');
</script>
Alert
<script>
// using alert
alert('Hello World');
</script>
Primitive Data Types − This is the predefined data type that is provided by JavaScript for different
usages. These are also known as the in-built data types.
Primitive Datatypes
Different types of Primitive Datatype are −
[Link] −This data type can hold the decimal values as well as the without decimal values in
JavaScript.
Example 1
In the below example, we will be exploring the Number data type.
<html>
<head>
<title>Data Types</title>
</head>
<body>
<script>
var x = 3874772;
var y = 22/7;
</script>
</body>
</html>
Output:
Value of x: 3874772
Value of y: 3.142857142857143
2. String Datatype − The String datatype in JavaScript is used for representing a sequence of
characters that is surrounded by single or double quotes.
<html>
<head>
<title>Data Types</title>
</head>
<body>
<script>
</script>
</body>
</html>
Output:
3. Undefined − The undefined data type is used when the value of any request or response cannot be
defined by JavaScript. For example: Initializing a number without value.
<html>
<head>
<title>Data Types</title>
</head>
<body>
<script>
let x;
x = undefined
</script>
</body>
</html>
Output
Value of x: undefined
x: undefined
3. Boolean − The boolean data type only accepts two types of values i.e. either true or false.
<script>
let x = 5;
let y = 5;
let z = 6;
[Link]("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>
Non-primitive datatypes
The non-primitive data types are as follows −
1. Object − The objects in JavaScript are entities that have properties and methods. Everything in
Java is an Object.
<html>
<head>
<title>Data Types</title>
</head>
<body>
<script>
let student = {
firstName: "Gary",
lastName: "Phillips",
};
</script>
</body>
</html>
Output:
Example:
<p id="demo"></p>
<script>
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
2. Array − Arrays in JavaScript can be used for storing more than one element under a single name.
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
Declaring a 1D array −
// Call it with no arguments
var a = new Array();
Example 6
# [Link]
<html><head>
<title>Data Types</title></head><body>
<h1 style="color: red;">
Welcome To Tutorials Point
</h1>
<script>
var x = new Array();
var y = new Array(21);
var z = new Array("Hello", 21, "Tutorials", "Point", 32, 56);
[Link]("value of x: " + x);
[Link]("value of y: " + y);
[Link]("value of z: " + z);
</script></body></html>
Output
The above program will produce the following output in the Console.
value of x:
value of y: ,,,,,,,,,,,,,,,,,,,,
value of z: Hello,21,Tutorials,Point,32,56
Example:
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = cars[0];
</script>
[Link]
A JavaScript function is a block of code designed to perform a particular task.
<p id="demo"></p>
<script>
return p1 * p2;
</script>
Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
JavaScript Variable:
In this example, x, y, and z, are variables, declared with the var keyword:
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
[Link]("demo").innerHTML =
</script>
or
let x = 5;
let y = 6;
let z = x + y;
Or
x = 5;
y = 6;
z = x + y;
The var keyword is used in all JavaScript code from 1995 to 2015.
If you want your code to run in older browser, you must use var.
If you think the value of the variable can change, use let.
<script>
const price1 = 5;
const price2 = 6;
[Link]("demo").innerHTML =
</script>
The two variables price1 and price2 are declared with the const keyword.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same
name. If you declare a local variable or function parameter with the same name as a global variable,
you effectively hide the global variable. Take a look into the following example.
<html>
<!--
function checkscope( ) {
[Link](myVar);
//-->
</script>
</body>
</html>
Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
// Change paragraph:
</script>
</body>
</html>
Multi-line Comments
Multi-line comments start with /* and end with */.
This example uses a multi-line comment (a comment block) to explain the code:
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
*/
</script>
</body>
</html>
const Keyword
JavaScript const keyword is used to define constant values that can not changed once a value is set. The
value of a constant can't be changed through reassignment, and it can't be redeclared.
The scope of const is block-scoped it means it can not be accessed from outside of block. In case of
scope, it is much like variables defined using the let statement.
Constants can be either global or local to the block in which it is declared. Global constants do not
become properties of the window object, unlike var variables.
Copy
We don't have to use var or let keyword while using the const keyword. Also, we can define a list or a
simple value or a string etc as a constant.
const Pi = 3.14;
alert(Pi);
}
Output:
3.14
<!doctype html>
<head>
<style>
</style>
<title>const Statement</title>
</head>
<body>
<script>
// global scope
const x = 200;
// block scope
const x = 10;
// function scope
function show() {
const x = 20;
show();
[Link]("<br>Global x:"+x);
[Link]("<br>Global x:"+x);
</script>
</body>
</html>
Output:
JavaScript Operators
Operators (Arithmetic, Assignment, Comparison, Logical and Conditional Operator)
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
-- Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = x;
</script>
Or
<p id="demo"></p>
<script>
let a = 100;
let b = 50;
let x = a + b;
[Link]("demo").innerHTML = x;
</script>
Or
<p id="demo"></p>
<script>
let a = 3;
[Link]("demo").innerHTML = x;
</script>
Operators and Operands
The numbers (in an arithmetic operation) are called operands.
The operation (to be performed between the two operands) is defined by an operator.
100 + 50
Adding
The addition operator (+) adds numbers:
<p id="demo"></p>
<script>
let x = 5;
let y = 2;
let z = x + y;
[Link]("demo").innerHTML = z;
</script>
Subtracting
The subtraction operator (-) subtracts numbers.
let x = 5;
let y = 2;
let z = x - y;
Multiplying
The multiplication operator (*) multiplies numbers.
let x = 5;
let y = 2;
let z = x * y;
Dividing
The division operator (/) divides numbers.
let x = 5;
let y = 2;
let z = x / y;
Remainder
The modulus operator (%) returns the division remainder.
let x = 5;
let y = 2;
let z = x % y;
Incrementing
The increment operator (++) increments numbers.
let x = 5;
x++;
let z = x;
Decrementing
The decrement operator (--) decrements numbers.
let x = 5;
x--;
let z = x;
Comparison Operators
JavaScript provides comparison operators that compare two operands and return a boolean
value true or false.
Operators Description
> Returns a boolean value true if the left-side value is greater than the right-side value; otherwise, returns false.
< Returns a boolean value true if the left-side value is less than the right-side value; otherwise, returns false.
>= Returns a boolean value true if the left-side value is greater than or equal to the right-side value; otherwise, returns
false.
<= Returns a boolean value true if the left-side value is less than or equal to the right-side value; otherwise, returns
false.
<!DOCTYPE html>
<html>
<body>
<p>
</p>
<script>
[Link]("p2").innerHTML += a === c;
[Link]("p3").innerHTML += a == x;
[Link]("p4").innerHTML += a != b;
[Link]("p5").innerHTML += a > b;
[Link]("p6").innerHTML += a < b;
[Link]("p7").innerHTML += a >= b;
[Link]("p8").innerHTML += a <= b;
</script>
</body>
</html>
Logical Operators
In JavaScript, the logical operators are used to combine two or more conditions. JavaScript
provides the following logical operators.
Operator Description
&& && is known as AND operator. It checks whether two operands are non-zero or not (0, false, undefined, null or ""
are considered as zero). It returns 1 if they are non-zero; otherwise, returns 0.
|| || is known as OR operator. It checks whether any one of the two operands is non-zero or not (0, false, undefined,
null or "" is considered as zero). It returns 1 if any one of of them is non-zero; otherwise, returns 0.
! ! is known as NOT operator. It reverses the boolean result of the operand (or condition). !false returns true,
and !true returns false.
<!DOCTYPE html>
<html>
<body>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var a = 5, b = 10;
</script>
</body>
</html>
Assignment Operators
JavaScript provides the assignment operators to assign values to variables with less key strokes.
Assignment operators Description
+= Sums up left and right operand values and assigns the result to the left operand.
-= Subtract right operand value from the left operand value and assigns the result to the left operand.
*= Multiply left and right operand values and assigns the result to the left operand.
/= Divide left operand value by right operand value and assign the result to the left operand.
%= Get the modulus of left operand divide by right operand and assign resulted modulus to the left
operand.
<!DOCTYPE html>
<html>
<body>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<p id="p6"></p>
<script>
var x = 5, y = 10;
x = y;
[Link]("p1").innerHTML = x;
x += 1;
[Link]("p2").innerHTML = x;
x -= 1;
[Link]("p3").innerHTML = x;
x *= 5;
[Link]("p4").innerHTML = x;
x /= 5;
[Link]("p5").innerHTML = x;
x %= 2;
[Link]("p6").innerHTML = x;
</script>
</body>
</html>
Conditional Operator
?: (Conditional operator)
The conditional operator is used as a shortcut for standard if statement. It takes three operands.
Syntax
Parameters
If the condition is true, the operator returns the value of expr1; otherwise, it returns the value of
expr2.
For example
status = (marks >= 30) ? "Pass" : "Fail"
The statement assigns value "Pass" to the variable status if marks are 30 or more. Otherwise, it
assigns the value of "Fail" to status.
<!DOCTYPE html>
<html>
<body>
<p id="p1"></p>
<p id="p2"></p>
<script>
var a = 10, b = 5;
var c = a > b? a : b;
var d = a > b? b : a;
[Link]("p1").innerHTML = c;
[Link]("p2").innerHTML = d;
</script>
</body>
</html>
3.5 Control Structure
conditional statements are used to perform different actions based on various conditions. The
conditional statement evaluates a condition before the execution of instructions.
When you write the code, you require to perform different actions for different decisions. You can
easily perform it by using conditional statements.
o if statement
o if….else statement
o if….else if….statement
o nested if statement
o switch statement
The if statement
It is one of the simplest decision-making statement which is used to decide whether a block of
JavaScript code will execute if a certain condition is true.
Syntax
1. if (condition) {
2. // block of code will execute if the condition is true
3. }
If the condition evaluates to true, the code within if statement will execute, but if the condition
evaluates to false, then the code after the end of if statement (after the closing of curly braces) will
execute.
Flowchart
For example
1. var x = 78;
2. if (x>70) {
3. [Link]("x is greater")
4. }
Output
x is greater
Syntax
1. if (condition)
2. {
4. }
5. else
6. {
8. }
If the condition is true, then the statements inside if block will be executed, but if the condition is false,
then the statements of the else block will be executed.
Flowchart
For example
2. if (x < y)
3. {
4. [Link]("y is greater");
5. }
6. else
7. {
8. [Link]("x is greater");
9. }
Output
x is greater
The if….else if…..else statement
It is used to test multiple conditions. The if statement can have multiple or zero else if statements and
they must be used before using the else statement. You should always be kept in mind that the else
statement must come after the else if statements.
Syntax
1. if (condition1)
2. {
4. }
5. else if (condition2)
6. {
7. // block of code will execute if the condition1 is false and condition2 is true
8. }
9. else
10. {
11. // block of code will execute if the condition1 is false and condition2 is false
12. }
Example
Output
c is greater
1. if (condition1)
2. {
3. Statement 1; //It will execute when condition1 is true
4. if (condition2)
5. {
6. Statement 2; //It will execute when condition2 is true
7. }
8. else
9. {
10. Statement 3; //It will execute when condition2 is false
11. }
12. }
Example
Output
The switch statement uses the break or default keywords, but both of them are optional. Let us
define these two keywords:
break: It is used within the switch statement for terminating the sequence of a statement. It is
optional to use. If it gets omitted, then the execution will continue on each statement. When it is used,
then it will stop the execution within the block.
default: It specifies some code to run when there is no case match. There can be only a single default
keyword in a switch. It is also optional, but it is recommended to use it as it takes care of unexpected
cases.
If the condition passed to switch doesn't match with any value in cases, then the statement under the
default will get executed.
Syntax
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Flowchart
Example
1. var num = 5;
2. switch(num) {
3. case 0 : {
4. [Link]("Sunday");
5. break;
6. }
7. case 1 : {
8. [Link]("Monday");
9. break;
10. }
11. case 2 : {
12. [Link]("Tuesday");
13. break;
14. }
15. case 3 : {
16. [Link]("Wednesday");
17. break;
18. }
19. case 4 : {
20. [Link]("Thursday");
21. break;
22. }
23. case 5 : {
24. [Link]("Friday");
25. break;
26. }
27. case 6 : {
28. [Link]("Saturday");
29. break;
30. }
31. default: {
32. [Link]("Invalid choice");
33. break;
34. }
35. }
Output
Friday
4. For Loop
Syntax
<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = [Link]("strr").value;
var i = [Link];
for(var j=i; j>=0; j--)
{
revstr = revstr+[Link](j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr" name="checkpalindrome"><br>
<input type="submit" value="Check" > </form>
</body>
</html>
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
let text = "";
for (let i = 0; i < [Link]; i++) {
text += cars[i] + "<br>";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
5. While Loop
Syntax
while (condition)
{
//Statements;
}
<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
[Link]("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
[Link](no3+"<br>");
}
</script>
</body>
</html>
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>
7. Do-While Loop
Syntax
do
{
//Statements;
}
while(condition);
<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
[Link](i+"<br>")
i++;
}
while (i <= 5)
</script>
</body>
</html>
Output:
0
1
2
3
4
5
In while loop, first it checks the condition and then executes the In Do – While loop, first it executes the program and then check
program. condition.
The condition will come before the body. The condition will come after the body.
If the condition is false, then it terminates the loop. It runs at least once, even though the conditional is false.
8. Break Statement
9. Continue Statement
Continue statement causes the loop to continue with the next iteration.
It skips the remaining code block.
<head>
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
<form>
</form>
</body></html>
<!DOCTYPE html>
<html>
<body>
<script>
function mouseOver() {
[Link]("demo").[Link] = "red";
}
function mouseOut() {
[Link]("demo").[Link] = "pink";
}
</script>
</body>
</html>
Mouseup,mousedown:
The onmousedown event occurs when a user presses a mouse button over an element.
The onmouseup event occurs when a user releases a mouse button over an element.
<!DOCTYPE html>
<html>
<body>
<script>
function mouseDown() {
[Link]("myP").[Link] = "red";
}
function mouseUp() {
[Link]("myP").[Link] = "green";
}
</script>
</body>
</html>
3.6.2 Form Event : (focus, submit, blur, change)
Attribute Description
onblur Some form validation object loos the focus, then event fired.
onfocus In the form <input>, <a> , <select> object has focus. Working on
this object then event fired.
On Blur:-
Definition and Usage
The onblur attribute fires the moment that the element loses focus.
Onblur is most often used with form validation code (e.g. when the user leaves a form
field).
<html>
<body>
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = [Link]("fname");
[Link] = [Link]();
</script>
</body>
</html>
Eg:2
<html>
<body>
<p>When you enter the input field, a function is triggered which sets the background color to yellow. When you
leave the input field, a function is triggered which sets the background color to red.</p>
<script>
function focusFunction() {
[Link]("myInput").[Link] = "yellow";
function blurFunction() {
[Link]("myInput").[Link] = "red";
</script>
</body>
</html>
onchange:
The onchange attribute fires the moment when the value of the element is changed.
Tip: This event is similar to the oninput event. The difference is that the oninput event
occurs immediately after the value of an element has changed, while onchange occurs
when the element loses focus. The other difference is that the onchange event also works
on <select> elements.
Supported HTML <input type="checkbox">, <input type="file">, <input
tags: type="password">, <input type="radio">, <input
type="range">, <input type="search">, <input type="text">,
<select> and <textarea>
<html>
<body>
<p>When you select a new car, a function is triggered which outputs the value of the
selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("mySelect").value;
[Link]("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Eg:2
<html>
<body>
<p>Modify the text in the input field, then click outside the field to fire the onchange
event.</p>
<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val);
}
</script>
</body>
</html>
onfocus:
<html>
<body>
<p>A function is triggered when one of the input fields get focus. The function changes the
background-color of the input field.</p>
First name: <input type="text" id="fname" >Last name: <input type="text" id="lname" >
<script>
function myFunction(x) {
[Link](x).[Link] = "yellow";
}
</script>
</body>
</html>
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
</form>
<script>
function myFunction() {
</script>
</body>
</html>
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form
validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
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.
Example:- 1
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
<body>
<form action = "/cgi-bin/[Link]" name = "myForm" > <table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Example:- 2
<html>
<body>
<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="[Link] >validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form name="myform" action="[Link]
validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
<html>
<body>
<script type="text/javascript">
function validate(){
var name=[Link];
var passwordlength=[Link];
var status=false;
if(name==""){
[Link]("namelocation").innerHTML=
" <img
src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH8AAAB/CAMAAADxY+0h
AAAAOVBMVEX///8AAACPj49oaGiBgYF+fn719fWpqalLS0sJCQk5OTmWlpbh4eGSkpJ7e3tu
bm51dXXa2tpTU1PaztA5AAACFElEQVRoge2ba6+DIAyGwbtTdNv//7HzxBi13IX5LjntRy080
hYskAohmrbr5f3Sd20jFnk9APBVHq9l9Dj88gGNaIF4KVvRQfmdQITeLr2A4qVkPvM3eQ/FH
TK8LfxB3CODhV/cxC+Yz3zmM5/5zGc+85n/2/xRlaUaIwjuBrF8tb5WwXhPg0i+2t6Xgfhya2
D5gDj+uCtMQfhpb2B2QRxfHTSqAHx10DcbII5fHjRk7cXXR3WzxxL4cvbg55N2Dr469SifTvz
zrJzD/uO5S6cLaqKbI/6oARxBWBHNLPOPRoDdBcT41vUiev2dSMfmIJyJlnW1iP//UMOaYoD
63u6mC/8/f+chn3id7zVumIuu8z3BFRqi1/maC44WoKN3L9MX8x/q4SrgTU6+5oJtlNQy7iU
6If+jQTg7nn6DbxypzSrf4OuebiJ9n8jXIp1e34SkaEn5P53pZwlKUdP2H9QCsaNP3v9Qj+8S
kp6m87VZsIk/8vPwtRm/infeZ+Nrc/5PfKteTr4hBgJ9n4nf0HnfNbfyweMH+x8c/+D5D17/w
Os/+P8H/v+D8x9w/gfOf8H5P3j/A97/gfe/4P0/+PwDfP4DPv8Cn/+Bzz/R57/o82/0+T/6/gN
9/4O+/0Lf/8HvP+H3v7mF+cxnPvOZz3zmM5/5v8FH17+g638Qwvx/zkfXf6LrX9H1v+j6Z3
T9N7j+/QPMnCdyYLGA3gAAAABJRU5ErkJggg=='/> Please enter your name";
status=false;
}else{
[Link]("namelocation").innerHTML=" <img
src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIMAAACNCAMAAACjSTkk
AAAAb1BMVEX///8AAAD8/Pzj4+Pu7u739/cEBATf39+tra309PS7u7uzs7PW1tbBwcHn5+eP
j4+ioqKWlpbPz8/JycmCgoIxMTFHR0cYGBiIiIhiYmJNTU17e3taWlpnZ2dsbGx0dHQoKCg4O
DggICAPDw9AQEApAh4hAAAE00lEQVR4nO1biZKqOBRNQiIhGwmojaJt2/b/f+NkcSGgNa/6
STJTxSnLogXN4e73kgZgwYIFCxYsWLBgwYL/D9D9LS/+AxSyo+1/1iongYodoMUuy+LBEtn
WMYAbkYWDBaEbu/5qBTc4FwO2hwHbIrlfhPXEzq+/8hRSM0DuhXt4w7ZKTSHw4Bt4k8Iug
y1YTRQ7v/zKsThWOWwB6QsM7uAoJF4/QB3uaoDwk+SgwL6vy3sKOVIV6gYMHIX0toBPAz
2kV4S75XILB9jlUIT4unmD88sdyVC4tB+Wwd0YDsmjo43OPNjBlcQ+Q4BG9CaAldPHNkfdp
G+m4CWxKTNQMI8EYd8+0tcLXgrwoYvvJvX6KKZgIVNTAJEtBArpFUHhMEdAk5qCXY4P1b
CCXVoCnoOMhAD79AxCgH5QyBEexQUOk4SNTcmNobjEXpm4o3P3q/YDW7BHNPWcAQFyi
DwCrn3+TEviGAeGI0lLwbURZigEmyUSp2tkbzjOUxA26V2CxbEJ6tS2YEvoODbBU/o8pX5ie
9zMsAYCr13d2eMuNobv1MEJ+dJtNaBgjWEOkKp6rWEe6WE1S3Aq6Hp//tnV7fMs2HzHWeL
81mSJfAjuroMceDk0T+6QnGMKsH0nBU+CRb/f47FxRvZ4jQzvJeGqwyj27Me9gh5dcHx7h9
/AMc7xXK0ZlQxQvVcMCFQ/Ew7wqwDXeYqbO0anrEDYOwmAZ1kgqKNC6PoshnyOLujf7ZQ
IHCYEHB71+qijgh8qfO+dKK202XFCgl5Py/GJN7vlA4hfRhpx9bIVevU1TJb26HOemsH/KB/f
78Gf6+N8Db/mGjN4EmZMwmnDGUNEgs1aOpGxcW4UKDejz46z1i3Ix6rVMD/XYD+iAGcf
+Iy1senHFOqZGVgf+Bj2ULdJ0wA/c9fy0wHPyBwfMWNOVNsxiQiHBDN5NA0SEZoE/a3NTy
8FYbVymnv9Kwn2ioMtKlI9srSF4zSRB8xTzE+ApmXbHft0nR0+vxBDm7DHrp9TOKUcuOCn
FDZJn6GjSZJwSBEhB5iW+jZRpJ63TBK2j5BpQScU1qkpAHUelbGz1ZAv4FLjuJbhaSl44DhW
7jNQAKDLa5AexceAQvqnNAGDODV7DfkcCIiHIHiePYjIW0Qwy0MOAgE4RAY/Cc2zFxOFFO5
brYy7QbHvNPc4645UnzVmm3f8GVwbPtO8489R7k4q9fOyJ0i/32rBggULFixYsGDBggUL3oH
q0c6g28tPyUkVtsqhsBcBPe177p/8VV9GlfslVVT3UaQI+00EjwYQjh1iXdka0moCGJZdU3HQ
GiwMJn8zs2Et01JgoTvaY9YoKnjR84IWJW9pQ0BJC8kVk1wAREBlUKHLXgvNNDAY0BPqsGH
K8OPvByZVJ2ir60IzJjjra2b/wrqsRWcKsZeA1EpyWVMta1BogJiRuu4kqTvNpJagA8ZwwBt78
GtlkLLWSneik7Lk9oZbVjVUF506GdyuNSAd4axdS1p2Tg6kkhyvCyPWWtVIGLAGuEdcAsvh1
3JAui2rRmmGqdKYsqIsrH65MtguVIqmwUZJWpUC+3EpoRRIBBqNGl1RirixeiS6ZtKwFMMC
dHeLdy929zp0mzmg8P+QCFz9Dd38FQVHBfdrHuT+jdc/rKwtGmdQE7UAAAAASUVORK5C
YII='/>";
status=true;
}
if(passwordlength<6){
[Link]("passwordlocation").innerHTML=
" <img
src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH8AAAB/CAMAAADxY+0h
AAAAOVBMVEX///8AAACPj49oaGiBgYF+fn719fWpqalLS0sJCQk5OTmWlpbh4eGSkpJ7e3tu
bm51dXXa2tpTU1PaztA5AAACFElEQVRoge2ba6+DIAyGwbtTdNv//7HzxBi13IX5LjntRy080
hYskAohmrbr5f3Sd20jFnk9APBVHq9l9Dj88gGNaIF4KVvRQfmdQITeLr2A4qVkPvM3eQ/FH
TK8LfxB3CODhV/cxC+Yz3zmM5/5zGc+85n/2/xRlaUaIwjuBrF8tb5WwXhPg0i+2t6Xgfhya2
D5gDj+uCtMQfhpb2B2QRxfHTSqAHx10DcbII5fHjRk7cXXR3WzxxL4cvbg55N2Dr469SifTvz
zrJzD/uO5S6cLaqKbI/6oARxBWBHNLPOPRoDdBcT41vUiev2dSMfmIJyJlnW1iP//UMOaYoD
63u6mC/8/f+chn3id7zVumIuu8z3BFRqi1/maC44WoKN3L9MX8x/q4SrgTU6+5oJtlNQy7iU
6If+jQTg7nn6DbxypzSrf4OuebiJ9n8jXIp1e34SkaEn5P53pZwlKUdP2H9QCsaNP3v9Qj+8S
kp6m87VZsIk/8vPwtRm/infeZ+Nrc/5PfKteTr4hBgJ9n4nf0HnfNbfyweMH+x8c/+D5D17/w
Os/+P8H/v+D8x9w/gfOf8H5P3j/A97/gfe/4P0/+PwDfP4DPv8Cn/+Bzz/R57/o82/0+T/6/gN
9/4O+/0Lf/8HvP+H3v7mF+cxnPvOZz3zmM5/5v8FH17+g638Qwvx/zkfXf6LrX9H1v+j6Z3
T9N7j+/QPMnCdyYLGA3gAAAABJRU5ErkJggg=='/> Password must be greater than 6";
status=false;
}else{
[Link]("passwordlocation").innerHTML=" <img
src='[Link]
}
return status;
}
</script>
<form name="f1" action="[Link]
validate()">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/>
<span id="namelocation" style="color:red"></span></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"/>
<span id="passwordlocation" style="color:red"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/> </td></tr>
</table>
</form>
</body>
</html>
There are many criteria that need to be follow to validate the email id such as:
<html>
<body>
<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="[Link] >validateemail();">
Email: <input type="text" name="email"><br/>