<form name="validation" onSubmit="return checkbae()">
Please input a valid email address:<br />
<input type="text" size=18 name="emailcheck">
<input type="submit" value="Submit">
</form>
<script language="JavaScript1.2">
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts
Complex Login JavaScript
<script type = "text/javascript">
// Note: Like all Javascript password scripts, this is hopelessly insecure as the user can see
//the valid usernames/passwords and the redirect url simply with View Source.
// And the user can obtain another three tries simply by refreshing the page.
//So do not use for anything serious!
var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;
// Note: Like all Javascript password scripts, this is hopelessly insecure as the user can see
//the valid usernames/passwords and the redirect url simply with View Source.
// And the user can obtain another three tries simply by refreshing the page.
//So do not use for anything serious!
var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;
Simple Login JavaScript
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
Form Validation
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Java Calculator
The DOM
The Document Object Model is a way to manipulate the structure and style of an HTML page. It represents the internals of the page as the browser sees it, and allows the developer to alter it with JavaScript.
Trees and Branches :
HTML is an XML-like structure in that the elements form a structure of parents’ nodes with children, like the branches of a tree. There is one root element (html) with branches like head and body, each with their own branches. For this reason, the DOM is also called the DOM tree.
Modifying the DOM, by picking an element and changing something about it, is something done often in JavaScript. To access the DOM from JavaScript, the document object is used. It’s provided by the browser and allows code on the page to interact with the content.
Getting an Element :
The first thing to know is how to get an element. There are a number of ways of doing it, and browsers support different ones. Starting with the best supported we’ll move through to the latest, and most useful, versions.
By ID :
document.getElementById is a method for getting hold of an element - unsurprisingly - by its ID.
var pageHeader = document.getElementById('page-header');
The pageHeader element can then be manipulated - its size and color can be changed, and other code can be declared to handle the element being clicked on or hovered over. It’s supported in pretty much all the browsers you need to worry about.
Notice that getElementById is a method of the document object. Many of the methods used to access the page are found on the document object.
By Tag Name :
document.getElementsByTagName works in much the same way as getElementById, except that it takes a tag name (a, ul, li, etc) instead of an ID and returns a NodeList, which is essentially an array of the DOM Elements.
By Class Name :
document.getElementsByClassName returns the same kind of NodeList as getElementsByTagName, except that you pass a class name to be matched, not a tag name.
By CSS Selector :
A couple of new methods are available in modern browsers that make selecting elements easier by allowing the use of CSS selectors. They are document.querySelector and document.querySelectorAll.
var pageHeader = document.querySelector('#header');
var buttons = document.querySelectorAll(.btn);
querySelector, like getElementById, returns only one element whereas querySelectorAll returns a NodeList. If multiple elements match the selector you pass to querySelector, only the first will be returned.
Trees and Branches :
HTML is an XML-like structure in that the elements form a structure of parents’ nodes with children, like the branches of a tree. There is one root element (html) with branches like head and body, each with their own branches. For this reason, the DOM is also called the DOM tree.
Modifying the DOM, by picking an element and changing something about it, is something done often in JavaScript. To access the DOM from JavaScript, the document object is used. It’s provided by the browser and allows code on the page to interact with the content.
Getting an Element :
The first thing to know is how to get an element. There are a number of ways of doing it, and browsers support different ones. Starting with the best supported we’ll move through to the latest, and most useful, versions.
By ID :
document.getElementById is a method for getting hold of an element - unsurprisingly - by its ID.
var pageHeader = document.getElementById('page-header');
The pageHeader element can then be manipulated - its size and color can be changed, and other code can be declared to handle the element being clicked on or hovered over. It’s supported in pretty much all the browsers you need to worry about.
Notice that getElementById is a method of the document object. Many of the methods used to access the page are found on the document object.
By Tag Name :
document.getElementsByTagName works in much the same way as getElementById, except that it takes a tag name (a, ul, li, etc) instead of an ID and returns a NodeList, which is essentially an array of the DOM Elements.
By Class Name :
document.getElementsByClassName returns the same kind of NodeList as getElementsByTagName, except that you pass a class name to be matched, not a tag name.
By CSS Selector :
A couple of new methods are available in modern browsers that make selecting elements easier by allowing the use of CSS selectors. They are document.querySelector and document.querySelectorAll.
var pageHeader = document.querySelector('#header');
var buttons = document.querySelectorAll(.btn);
querySelector, like getElementById, returns only one element whereas querySelectorAll returns a NodeList. If multiple elements match the selector you pass to querySelector, only the first will be returned.
Arrays
Arrays are lists of any kind of data, including other arrays. Each item in the array has an index - a number - which can be used to retrieve an element from the array.
The indices start at 0; that is, the first element in the array has the index 0, and subsequent elements have incrementally increasing indices, so the last element in the array has an index one less than the length of the array.
In JavaScript, you create an array using the array-literal syntax:
var emptyArray = [];
var shoppingList = ['Milk', 'Bread', 'Beans'];
You retrieve a specific element from an array using square bracket syntax:
shoppingList[0];
Milk
It’s also possible to set the value at a particular index, again using the square bracket syntax:
shoppingList[1] = 'Cookies';
// shoppingList is now ['Milk', 'Cookies', 'Beans']
You can find the number of elements in the array using its length property:
shoppingList.length;
3
You can use push and pop methods to add and remove elements from the end of the array:
shoppingList.push('A new car');
// shoppingList is now ['Milk', 'Break', 'Beans', 'A new car']
shoppingList.pop();
// shoppingList is back to ['Milk', 'Break', 'Beans']
Here’s an example that creates, pushes, pops and iterates over an array, passing each name to a function called helloFrom. helloFrom returns a string with a greeting: “Hello from ” and then the person’s name. After the pushing and popping, the final list of people is: “Tom”, “Yoda”, “Ron” and “Bob”.
var helloFrom = function (personName) {
return "Hello from " + personName;
}
var people = ['Tom', 'Yoda', 'Ron'];
people.push('Bob');
people.push('Dr Evil');
people.pop();
for (var i=0; i < people.length; i++) {
var greeting = helloFrom(people[i]);
alert(greeting);
}
The indices start at 0; that is, the first element in the array has the index 0, and subsequent elements have incrementally increasing indices, so the last element in the array has an index one less than the length of the array.
In JavaScript, you create an array using the array-literal syntax:
var emptyArray = [];
var shoppingList = ['Milk', 'Bread', 'Beans'];
You retrieve a specific element from an array using square bracket syntax:
shoppingList[0];
Milk
It’s also possible to set the value at a particular index, again using the square bracket syntax:
shoppingList[1] = 'Cookies';
// shoppingList is now ['Milk', 'Cookies', 'Beans']
You can find the number of elements in the array using its length property:
shoppingList.length;
3
You can use push and pop methods to add and remove elements from the end of the array:
shoppingList.push('A new car');
// shoppingList is now ['Milk', 'Break', 'Beans', 'A new car']
shoppingList.pop();
// shoppingList is back to ['Milk', 'Break', 'Beans']
Here’s an example that creates, pushes, pops and iterates over an array, passing each name to a function called helloFrom. helloFrom returns a string with a greeting: “Hello from ” and then the person’s name. After the pushing and popping, the final list of people is: “Tom”, “Yoda”, “Ron” and “Bob”.
var helloFrom = function (personName) {
return "Hello from " + personName;
}
var people = ['Tom', 'Yoda', 'Ron'];
people.push('Bob');
people.push('Dr Evil');
people.pop();
for (var i=0; i < people.length; i++) {
var greeting = helloFrom(people[i]);
alert(greeting);
}
Objects
JavaScript objects are like a real life objects; they have properties and abilities. A JavaScript object is, in that sense, a collection of named properties and methods - a function. An object can be stored in a variable, and the properties and methods accessed using the dot syntax.
A human, for example, has a name and an age, and could talk, move or learn JavaScript. Name and age are properties of the human, and are essentially pieces of data. Talking, moving and learning are more like functions - there’s some complex behavior involved. When a JavaScript object has such an ability, it is called a method.
Variables can hold objects, and creating an object is done using a special syntax signified by braces:
var jedi = {
name: "Yoda",
age: 899,
talk: function () { alert("another... Sky... walk..."); }
};
The Jedi’s name and age are properties - they are essentially variables within the object and can store anything a variable can. talk is a property that holds a function - a method.
You can get data back out of an object using the dot syntax:
jedi.name;
Yoda
jedi.age;
899
jedi.talk();
//produces an alert box
You can also reassign properties of an object:
jedi.name = "Mace Windu";
And add new ones on the fly:
jedi.lightsaber = "purple";
Properties can be any kind of data including objects and arrays. Adding an object as a property of another object creates a nested object:
var person = {
age: 122
};
person.name = {
first: "Jeanne",
last: "Calment"
};
Creating an empty object and adding properties and methods to it is possible too:
var dog = {};
dog.bark = function () { alert("Woof!"); };
A human, for example, has a name and an age, and could talk, move or learn JavaScript. Name and age are properties of the human, and are essentially pieces of data. Talking, moving and learning are more like functions - there’s some complex behavior involved. When a JavaScript object has such an ability, it is called a method.
Variables can hold objects, and creating an object is done using a special syntax signified by braces:
var jedi = {
name: "Yoda",
age: 899,
talk: function () { alert("another... Sky... walk..."); }
};
The Jedi’s name and age are properties - they are essentially variables within the object and can store anything a variable can. talk is a property that holds a function - a method.
You can get data back out of an object using the dot syntax:
jedi.name;
Yoda
jedi.age;
899
jedi.talk();
//produces an alert box
You can also reassign properties of an object:
jedi.name = "Mace Windu";
And add new ones on the fly:
jedi.lightsaber = "purple";
Properties can be any kind of data including objects and arrays. Adding an object as a property of another object creates a nested object:
var person = {
age: 122
};
person.name = {
first: "Jeanne",
last: "Calment"
};
Creating an empty object and adding properties and methods to it is possible too:
var dog = {};
dog.bark = function () { alert("Woof!"); };
Functions
Functions are reusable blocks of code that carry out a specific task. To execute the code in a function you call it. A function can be passed arguments to use, and a function may return a value to whatever called it.
To create a function, use the function keyword. You then list the arguments in parentheses, and then supply a block that contains the function’s code. Here’s a function that adds two numbers:
var add = function (a, b) {
return a + b;
};
a and b are the function’s parameters, and the value it returns is signified by the return keyword. The return keyword also stops execution of the code in the function; nothing after it will be run.
var result = add(1, 2); // result is now 3
This calls add with the arguments 1 and 2, which, inside add, will be saved in the variables a and b.
To create a function, use the function keyword. You then list the arguments in parentheses, and then supply a block that contains the function’s code. Here’s a function that adds two numbers:
var add = function (a, b) {
return a + b;
};
a and b are the function’s parameters, and the value it returns is signified by the return keyword. The return keyword also stops execution of the code in the function; nothing after it will be run.
var result = add(1, 2); // result is now 3
This calls add with the arguments 1 and 2, which, inside add, will be saved in the variables a and b.
Looping
Loops are a way of repeating the same block of code over and over. There are two types of commands for looping. For and While.
While :
A while loop repeats a block of code while a condition is true. Like an if statement, the condition is found in parentheses.
Example :
var a = 1;
while (a < 10) {
alert(a);
a = a+ 1;
}
// i is now 10
For :
A for loop is similar to an if statement, but it combines three semicolon-separated pieces information between the parentheses: initialization, condition and a final expression.
The initialization part is for creating a variable to let you track how far through the loop you are - like i in the while example; the condition is where the looping logic goes - the same as the condition in the while example; and the final expression is run at the end of every loop.
Example:
for (var z = 1; z < 10; z++) {
alert(z);
}
This gives us alert boxes containing the numbers 1 to 10 in order.
By the way, z++ is equivalent to z = z + 1
While :
A while loop repeats a block of code while a condition is true. Like an if statement, the condition is found in parentheses.
Example :
var a = 1;
while (a < 10) {
alert(a);
a = a+ 1;
}
// i is now 10
For :
A for loop is similar to an if statement, but it combines three semicolon-separated pieces information between the parentheses: initialization, condition and a final expression.
The initialization part is for creating a variable to let you track how far through the loop you are - like i in the while example; the condition is where the looping logic goes - the same as the condition in the while example; and the final expression is run at the end of every loop.
Example:
for (var z = 1; z < 10; z++) {
alert(z);
}
This gives us alert boxes containing the numbers 1 to 10 in order.
By the way, z++ is equivalent to z = z + 1
Conditional operation
Logic is used to make decisions in code; choosing to run one piece of code or another depending on the comparisons made. This requires use of something called a conditional. There are a few different conditionals that you might want to use, but we’ll just focus the one used most commonly: if.
If:
It’s very simple: if some logic (the condition) is true, run a block of code. You can also supply more code to be run if the condition is not true, and supply additional conditions and blocks of code to optionally be run. These forms are called if-else, as you’ll see below.
The most simple if statement looks something like this:
Syntax:
if (condition)
{
code to be executed if condition is true
}
Example:
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()
if (time==11)
{ document.write("<em>Lunch-time!</em>") }
</script>
If-else:
The if-else form of an if statement is used to run an alternative piece of code if the conditional is not true. The code in the if block below will be ignored, for example - only the code in the else block will be run.
Syntax:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example:
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>
You should use the if....else if...else statement if you want to select one of many sets of lines to execute.
Syntax:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>")
}
else
{
document.write("<b>Hello World!</b>")
}
</script>
Syntax:
switch(n)
{
case 1:
execute code block 1
break
case 2:
execute code block 2
break
default:
code to be executed if n is
different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}
</script>
If:
It’s very simple: if some logic (the condition) is true, run a block of code. You can also supply more code to be run if the condition is not true, and supply additional conditions and blocks of code to optionally be run. These forms are called if-else, as you’ll see below.
The most simple if statement looks something like this:
Syntax:
if (condition)
{
code to be executed if condition is true
}
Example:
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()
if (time==11)
{ document.write("<em>Lunch-time!</em>") }
</script>
If-else:
The if-else form of an if statement is used to run an alternative piece of code if the conditional is not true. The code in the if block below will be ignored, for example - only the code in the else block will be run.
Syntax:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example:
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>
If...else if...else Statement
You should use the if....else if...else statement if you want to select one of many sets of lines to execute.
Syntax:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>")
}
else
{
document.write("<b>Hello World!</b>")
}
</script>
Switch
You should use the switch statement if you want to select one of many blocks of code to be executed.Syntax:
switch(n)
{
case 1:
execute code block 1
break
case 2:
execute code block 2
break
default:
code to be executed if n is
different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}
</script>
Logical
A really important part of programming is being able to compare values in order to make decisions in code. When a comparison is made the outcome is either true or false; a special kind a of data called a boolean. This is logic.
Equality :
To find out when two values are equal, use the triple equals operator (“===”).
15.234 === 15.234
Condition: true
We can also determine if two values are not equal using the triple not equal operator (“!==”).
15.234 !== 18.4545
Condition: true
It’s important to know that strings containing a number and an actual number are not equal.
'10' === 10
Condition: false
Greater than and less than :
Comparing two numbers is useful, for example, to determine which of two is larger or smaller. This first example is a comparison of 10 and 5 to see if 10 is larger, using the greater than operator (“>”).
10 > 5
Condition: true
Next we use the less than operator (“<”) to determine if the left value is smaller.
20.4 < 20.2
Condition: false
Combined comparisons :
Combining a comparison of equality and size can be done with the greater than or equal to and less than or equal to operators (“>=” and “<=” respectively).
10 >= 10
Condition: true
10 <= 5
Condition: false
Equality :
To find out when two values are equal, use the triple equals operator (“===”).
15.234 === 15.234
Condition: true
We can also determine if two values are not equal using the triple not equal operator (“!==”).
15.234 !== 18.4545
Condition: true
It’s important to know that strings containing a number and an actual number are not equal.
'10' === 10
Condition: false
Greater than and less than :
Comparing two numbers is useful, for example, to determine which of two is larger or smaller. This first example is a comparison of 10 and 5 to see if 10 is larger, using the greater than operator (“>”).
10 > 5
Condition: true
Next we use the less than operator (“<”) to determine if the left value is smaller.
20.4 < 20.2
Condition: false
Combined comparisons :
Combining a comparison of equality and size can be done with the greater than or equal to and less than or equal to operators (“>=” and “<=” respectively).
10 >= 10
Condition: true
10 <= 5
Condition: false
Operators
Operator is used for do mathematical calculations. We assign airthmatic values to custom variables then we used operators. There are many types of operators such as: + , - , * and / .
Example :
a = 1;
b = 3;
c = a + b;
a = 1;
b = 3;
c = a - b;
a = 1;
b = 3;
c = a * b;
a = 1;
b = 3;
c = a / b + a ;
Example :
a = 1;
b = 3;
c = a + b;
a = 1;
b = 3;
c = a - b;
a = 1;
b = 3;
c = a * b;
a = 1;
b = 3;
c = a / b + a ;
Variables and Data
Variable is used to store or declare user's data from any type of input source. Such as data recieved or submit from input boxes or another input elements. So variable has a name and value.
Example:
<script type="text/javascript">
var name = "Hege"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>
Example 2:
var name = "Sarib Ali";
var b = "123456";
var email = "aaaa@aaa.aaa"
Example:
<script type="text/javascript">
var name = "Hege"
document.write(name)
document.write("<h1>"+name+"</h1>")
</script>
Example 2:
var name = "Sarib Ali";
var b = "123456";
var email = "aaaa@aaa.aaa"
Introduction
Mostly, JavaScript runs in your web browser along side HTML and CSS, and can added to any web page using a script tag. The script element can either contain JavaScript directly (internal) or link to an external resource via a src attribute (external).
Internal :
You can just put the JavaScript inside a script element:
<script>
alert("Hello, world.");
</script>
External
:An external JavaScript resource is a text file with a .js extension, just like an external CSS resource with a .css extension.
To add a JavaScript file to your page, you just need to use a script tag with a src attribute pointing to the file. So, if your file was called script.js and sat in the same directory as your HTML file, your script element would look like this:
<script src="script.js"></script>
Internal :
You can just put the JavaScript inside a script element:
<script>
alert("Hello, world.");
</script>
External
:An external JavaScript resource is a text file with a .js extension, just like an external CSS resource with a .css extension.
To add a JavaScript file to your page, you just need to use a script tag with a src attribute pointing to the file. So, if your file was called script.js and sat in the same directory as your HTML file, your script element would look like this:
<script src="script.js"></script>
Subscribe to:
Posts (Atom)