Javascript
What is JavaScript ?
JavaScript
is:
JavaScript is a lightweight,
interpreted programming
language
Complementary to and
integrated with Java
Complementary to and
integrated with HTML
Open and cross-platform
Advantages of JavaScript:
The
merits of using JavaScript are:
Less server interaction: You can validate
user input before sending the page off to the
server. This saves server traffic, which means
less load on your server.
Immediate feedback to the visitors: They
don't have to wait for a page reload to see if
they have forgotten to enter something.
Increased interactivity: You can create
interfaces that react when the user hovers
over them with a mouse or activates them
via the keyboard.
Limitations with JavaScript:
Client-side
JavaScript does not
allow the reading or writing of
files. This has been kept for
security reason.
JavaScript can not be used for
Networking applications because
there is no such support
available.
JavaScript doesn't have any
multithreading or multiprocess
Include <script>
There
is a flexibility given to include
JavaScript code anywhere in an HTML
document. But there are following most
preferred ways to include JavaScript in
your HTML file.
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and
<head>...</head> sections.
Script in and external file and then
include in <head>...</head> section.
JavaScript in <head>...</head> section:
If
you want to have a script run
on some event, such as when a
user clicks somewhere, then you
will place that script in the head
as follows:
Example
<html> <head>
<script type="text/javascript">
<!-- function sayHello() {
alert("Hello World") } //-->
</script> </head>
<body> <input type="button"
onclick="sayHello()" value="Say
Hello" /> </body> </html
JavaScript in <body>...</body> section:
If
you need a script to run as the
page loads so that the script
generates content in the page,
the script goes in the <body>
portion of the document. In this
case you would not have any
function defined using JavaScript:
Example:
<html>
<head>
</head>
<body> <script
type="text/javascript">
<!
document.write("Hello World")
//--> </script> <p>This is web
page body </p> </body>
</html>
JavaScript DataTypes:
JavaScript
allows you to work
with three primitive data types:
Numbers eg. 123, 120.50 etc.
Strings of text e.g. "This text
string" etc.
Boolean e.g. true or false.
Example:
<script type="text/javascript">
<!
var age = 20;
if( age > 18 )
{ document.write("<b>Qualifies
for driving</b>"); }
//--> </script>
Switch case
<script type="text/javascript">
var grade='A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break; case 'D':
document.write("Not so good<br />");
break; case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />") } d
Javascript if-else
<html>
<head>
<script
type="text/javascript">
var age=23;
if(age>18)
{
document.write("adult");
}
</script>
</head>
</html>
Javascript Output Function
Document.write();
alert();
document.getElementById("demo")
.innerHTML = x
Example
given in next slide.
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">
<br>
Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = Number(y) + Number(z);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Date ()
<html>
<head>
<script>
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
h+":"+m+":"+s;
document.getElementById('txt').innerHTML
var t = setTimeout(function(){startTime()},500);
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
</script>
Javascript form validation
Form
validation normally used to occur at
the server, after the client had entered
all the necessary data and then pressed
the Submit button. If the data entered by
a client was incorrect or was simply
missing, the server would have to send
all the data back to the client and
request that the form be resubmitted
with correct information. This was really
a lengthy process which used to put a lot
of burden on the server.
Continue..
JavaScript
provides a way to validate form's
data on the client's computer before sending it
to the web server. Form validation generally
performs two functions.
Basic Validation First of all, the form must
be checked to make sure all the mandatory
fields are filled in. It would require just a loop
through each field in the form and check for
data.
Data Format Validation Secondly, the data
that is entered must be checked for correct
form and value. Your code must include
appropriate logic to test correctness of data.
..\internet
technology\regis.html
Design a calculator
Requirements
display area for numbers
Buttons for 0,1,2, up to 9
A decimal point button
A button to change the sign (+/-)
Clear and all clear (C, AC buttons)
Function buttons (* / + -)
An exponent button (EXP)
A 'calculate' button (The = button)
<div
align="center">
<table width="30%"
border="4"> <tr>
<td
colspan="2"align="center">Displ
ay Area</td></tr>
<tr><td>Numeric Buttons</td>
<td>Function Buttons</td>
</tr></table></div>
<input
type="button">
Which gives us a general-purpose
button. To each of these buttons
we'll attach a:
OnClick="DoSomething()"
'event handler', so that when we
click on the button, we can
expect a response.
More detailed HTML for basic
calculator
<FORM name="Calculator">
<table border="4">
<tr> <!--TOP PANEL------>
<td colspan="2">A Simple JavaScript Calculator<br>
<input type="text" maxlength="40" size="30"
name="Display"> </td> </tr>
<!--END TOP PANEL--->
<tr> <td> <!--LEFT PANEL------>
<table> <tr> <td><input type="button" value="7"></td>
<td><input type="button" value="8">
</td> <td><input type="button" value="9"></td> </tr>
<tr> {all other rows of digits are similar..} </tr> </table>
</td>
<!--END LEFT PANEL--> <td> <!--RIGHT PANEL----->
<table> {right panel is similar in overall structure to
left} </table> </td><!--END RIGHT PANEL->
</tr></table>
output
..\internet
.html
technology\calculator1
Email validation
..\internet
technology\email.html
Phone Number Validation.
.\internet technology\phone.html
Javascript Array
An
array is a special variable, which can
hold more than one value at a time.
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").i
nnerHTML = cars;
</script>
Push operation
<html>
<body>
<p>Click the button to add new elements to the array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.push("Kiwi", "Lemon", "Pineapple");
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
</html>
JavaScript Regular Expressions
A
regular expression is a sequence of
characters that forms a search pattern.
When you search for data in a text, you
can use this search pattern to describe
what you are searching for.
A regular expression can be a single
character, or a more complicated pattern.
Regular expressions can be used to
perform all types of text search and
text replace operations.
regular expression is an object
that describes a pattern of
characters.
Regular expressions are used to
perform pattern-matching and
"search-and-replace" functions on
text.
Syntax
/pattern/modifiers;
Example
var
patt = /w3schools/i
i Perform case-insensitive matching
g Perform a global match (find all
matches rather than stopping after
the first match)
m Perform multiline matching
[abc]
[^abc]
[0-9]
[^0-9]
Find any character
between the brackets
Find any character
NOT between the
brackets
Find any digit
between the brackets
Find any digit NOT
between the brackets
Example
var
str = "Visit W3Schools";
var n = str.search(/w3schools/i);
Output:
Use String replace() With a Regular
Expression
<html>
<body>
<p>Replace "microsoft" with "W3Schools" in the
paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
var str =
document.getElementById("demo").innerHTML;
var txt = str.replace(/microsoft/i,"W3Schools");
document.getElementById("demo").innerHTML
= txt;
}
Replace "microsoft" with "W3Scho
</script>
in the paragraph below:
</body>
Please visit Microsoft!
</html>
Check input for 5 digit
number
<html>
<body>
<script>
function checkpostal()
{
var re5digit=/^\d{5}$/
if
(document.myform.myinput.value.search(re5digit)=
=-1)
alert("Please enter a valid 5 digit number
inside form")
}
</script>
<form name="myform">
<input type="text" name="myinput" size=15>
<input type="button" onClick="checkpostal()"
value="check">
</form>
</body>
var re5digit=/^\d{5}$/
^
indicates the beginning of the
string. Using a ^ meta character
requires that the match start at
the beginning.
\d indicates a digit character and
the {5} following it means that
there must be 5 consecutive digit
characters.
$ indicates the end of the string.
Using a $ meta character
<html>
<body>
<p>Click the button to perfom a global search for the
letters "ain" in a string, and display the matches.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/ain/g);
document.getElementById("demo").innerHTML = res;
}
Click the button to perform a global
</script>
search for the letters "ain" in a string,
</body>
and display the matches.
</html>
ain,ain,ain
Example
Perform a global, case-insensitive search for "ain":
var
str = "The rain in SPAIN stays
mainly in the plain";
var res = str.match(/ain/gi);
Output:
ain,AIN,ain,ain
var
myRegExp = /\$\d?\d\.\d\d/;
var myText = " The hot dog cost
$1.75!";
This expression will match the dollar sign,
followed by one or two digits, followed by
the decimal point (i.e., period), followed
by two digits. From Table 2, you can see
the "?" character means match 0 or 1 of
the preceding item. In this expression, it
means match zero or one digits.