JavaScript Overview and Basics Guide
JavaScript Overview and Basics Guide
Java Script
JavaScript started life as LiveScript, but Netscape changed the name, possibly because of
the excitement being generated by [Link] JavaScript. JavaScript made its first appearance
in Netscape 2.0 in 1995 with a name LiveScript.
the language has been embedded in Netscape, Internet Explorer, and other web browsers
JavaScript is:
The script should be included in or referenced by an HTML document for the code to be
interpreted by the browser.
It means that a web page need no longer be static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism features many advantages over traditional server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid
e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries
are valid they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation,
and other actions that the user explicitly or implicitly initiates.
Advantages of JavaScript:
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.
Richer interfaces: You can use JavaScript to include
such items as drag-and-drop components and sliders
to give a Rich Interface to your site visitors.
Limitations with JavaScript:
We can not treat JavaScript as a full fledged programming
language. It lacks the following important features:
One of JavaScript's strengths is that expensive development tools are not usually required. You can
start with a simple text editor such as Notepad.
Since it is an interpreted language inside the context of a web browser, you don't even need to buy a
compiler.
To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Few
of them are listed here:
Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage. FrontPage
also provides web developers with a number of JavaScript tools to assist in the creation of an
interactive web site.
Macromedia HomeSite 5: This provided a well-liked HTML and JavaScript editor, which will
manage their personal web site just fine.
Where JavaScript is Today ?
The ECMAScript Edition 4 standard will be the first update
to be released in over four years. JavaScript 2.0 conforms to
Edition 4 of the ECMAScript standard, and the difference
between the two is extremely minor.
The specification for JavaScript 2.0 can be found on the
following site: [Link]
Today, Netscape's JavaScript and Microsoft's JScript conform
to the ECMAScript standard, although each language still
supports features that are not part of the standard.
JavaScript Syntax
A JavaScript consists of JavaScript statements that are
placed within the <script>... </script> HTML tags in a
web page.
JavaScript code
</script>
Your First JavaScript Script:
Let us write our class example to print out
"Hello World".
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
[Link]("Hello World!")
//-->
</script></body>
</html>
We added an optional HTML comment that surrounds our
Javascript code.
This is to save our code from a browser that does not support
Javascript.
The comment ends with a "//-->". Here "//" signifies a comment in
Javascript, so we add that to prevent a browser from reading the
end of the HTML comment in as a piece of Javascript code.
Next, we call a function [Link] which writes a string into
our HTML document.
This function can be used to write text, HTML, or both. So above
code will display following result:
Hello World!
Whitespace and Line Breaks:
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if user's browser does not support JavaScript or JavaScript is not enabled then message
from </noscript> will be displayed on the screen.
JavaScript Placement in HTML File
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.
In the following section we will see how we can put JavaScript in different
ways:
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:
<html>
<head><script type="text/javascript">
<!--function sayHello()
{ alert("Hello World")}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This will produce following result: say Hello
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:
<html>
<head></head>
<body>
<script type="text/javascript">
<!--[Link]("Hello World")
//--></script>
<p>This is web page body </p>
</body>
</html>
This will produce following result:
Hello World
This is web page body
JavaScript Variables and DataTypes
JavaScript DataTypes:
One of the most fundamental characteristics of a programming language is the set of data types it
supports.
These are the type of values that can be represented and manipulated in a programming language.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single
value.
In addition to these primitive data types, JavaScript supports a composite data type known as object.
Note: Java does not make a distinction between integer values and floating-point values.
JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
JavaScript Variables:
Like many other programming languages, JavaScript has variables.
Variables can be thought of as named containers.
You can place data into these containers and then refer to the data
simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it.
Variables are declared with the var keyword as follows:
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the
same var keyword as follows:
<script type="text/javascript">
<!--
/ /-->
</script>
Storing a value in a variable is called variable initialization.
You can do variable initialization at the time of variable creation or later point in
time when you need that variable as follows:
For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable you can assign a value the time of
initialization as follows:
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note: Use the var keyword only for declaration or
initialization.
once for the life of any variable name in a document. You
should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript
variable can hold a value of any data type.
Unlike many other languages, you don't have to tell
JavaScript during variable declaration what type of value the
variable will hold.
The value type of a variable can change during the execution
of a program and JavaScript takes care of it automatically.
JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in
mind.
You should not use any of the JavaScript reserved keyword as
variable name. For example, break or boolean variable names are
not valid.
JavaScript variable names should not start with a numeral (0-9).
They must begin with a letter or the underscore character. For
example, 123test is an invalid variable name but _123test is a
valid one.
JavaScript variable names are case sensitive. For example, Name
and name are two different variables.
JavaScript Operators
What is an operator?
Simple answer can be given using expression 4 + 5 is equal
to 9.
Here 4 and 5 are called operands and + is called operator.
JavaScript language supports following type of operators.
Arithmetic Operators
Comparision Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
The Arithmatic Operators:
There are following arithmatic operators
supported by JavaScript language:
Assume variable A holds 10 and variable B
holds 20 then:
Note: Addition operator (+) works for Numeric
as well as Strings. e.g. "a" + 10 will give "a10".
Operator Description Example
So you need to make use of conditional statements that allow your program
to make correct decisions and perform right actions.
if statement
if...else statement
Syntax:
if (expression){
Syntax:
if (expression){
}else{
If expression is false then given statement(s) in the else block, are executed.
Example:
<script type="text/javascript">
<!--
}else{
//-->
</script>
Syntax:
if (expression 1){
}else{
}
There is nothing special about this code.
Example:
while (expression)
Example:
<!--
var count;
[Link]("<br />");
[Link]("Loop stopped!");
//-->
</script>
This will produce following result which is similar to while loop:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
JavaScript Loop Control
There may be a situation when you need to come out of a loop without
reaching at its bottom.
There may also be a situation when you want to skip a part of your
code block and want to start next iteration of the look.
These statements are used to immediately come out of any loop or to
start the next iteration of any loop respectively.
The break Statement:
Example:
This example illustrates the use of a break statement
with a while loop.
Notice how the loop breaks out early once x reaches
5 and reaches to [Link](..) statement just
below to closing curly brace:
<script type="text/javascript">
<!--
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 20){
if (x == 5){
break;
// breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
//-->
</script>
This will produce following result:
This eliminates the need of writing same code again and again.
<script type="text/javascript">
<!--
sayHello();
//-->
</script>
Function Parameters:
Till now we have seen function without a parameters.
But there is a facility to pass different parameters
while calling a function.
These passed parameters can be captured inside the
function and any manipulation can be done over those
parameters.
A function can take multiple parameters separated by
comma.
Example:
Let us do a bit modification in our sayHello function.
This time it will take two parameters:
<script type="text/javascript">
<!--
function sayHello(name, age)
{
alert( name + " is " + age + " years old.");
}
//-->
sayHello('Zara', 7 );
</script>
Note: We are using + operator to concatenate string and
number all together.
JavaScript does not mind in adding numbers into strings.
Now we can call this function as follows:
<script type="text/javascript">
<!--
sayHello('Zara', 7 );
//-->
</script>
The return Statement:
For example you can pass two numbers in a function and then
you can expect from the function to return their multiplication
in your calling program.
Example:
<!–
var result;
alert(result );
//-->
</script>
JavaScript Events
What is an Event ?
Another example of events are like pressing any key, closing window,
resizing window etc.
Say Hello
2. onsubmit event type:
Another most important event type is onsubmit.
This event occurs when you try to submit a form.
So you can put your form validation against this event
type.
Here is simple example showing its usage.
Here we are calling a validate() function before
submitting a form data to the webserver.
If validate() function returns true the form will be
submitted otherwise it will not submit the data.
Example:
<html><head>
<script type="text/javascript">
<!--
function validation()
{
all validation goes here ......... return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="[Link]" onsubmit="return
validate()".......
<input type="submit" value="Submit" />
</form></body></html>
3. onmouseover and onmouseout:
These two event types will help you to create nice
effects with images or even with text as well.
The onmouseover event occurs when you bring your
mouse over any element and the onmouseout occurs
when you take your mouse out from that element.
Example:
Following example shows how a division reacts
when we bring our mouse in that division:
<html><head>
<script type="text/javascript">
<!--
function over()
{
alert("Mouse Over");
}
function out()
{
alert("Mouse Out");
}//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2></div></body></html>
You can change different images using these two event types or you can create help
baloon to help your users.
JavaScript and Cookies
What are Cookies ?
Web Browser and Server use HTTP protocol to communicate and
HTTP is a stateless protocol.
But for a commercial website it is required to maintain session
information among different pages.
For example one user registration ends after completing many pages.
But how to maintain user's session information across all the web
pages.
In many situations, using cookies is the most efficient method of
remembering and tracking preferences, purchases, commissions, and
other information required for better visitor experience or site
statistics.
How It Works ?
Your server sends some data to the visitor's browser in the form of a
cookie. The browser may accept the cookie.
Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval.
Expires : The date the cookie will expire. If this is blank, the cookie
will expire when the visitor quits the browser.
Domain : The domain name of your site.
Path : The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.
Secure : If this field contains the word "secure" then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value : Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is
automatically transmitted between the web browser and web server, so CGI scripts
on the server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document
object. JavaScript can read, create, modify, and delete the cookie or cookies that
apply to the current web page.
Storing Cookies:
Syntax:
[Link] =
"key1=value1;key2=value2;expires=date";
Here expires attribute is optional. If you provide this attribute
with a valid date or time then cookie will expire at the given date
or time and after that cookies' value will not be accessible.
Note: Cookie values may not include semicolons, commas, or
whitespace. For this reason, you may want to use the JavaScript
escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the
corresponding unescape() function when you read the cookie
value.
Example:
Following is the example to set a customer name in input cookie
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( [Link] == "" ){
alert("Enter some value!");
return;
}
The prompt dialog box is very useful when you want to pop-up a text
box to get user input. Thus it enable you to interact with the user. The
user needs to fill in the field and then click OK.
This dialog box with two buttons: OK and Cancel. If the user clicks on
OK button the window method prompt() will return entered value
from the text box. If the user clicks on the Cancel button the window
method prompt() returns null.
You can use prompt dialog box as follows:
<head>
<script type="text/javascript">
<!--
var retVal = prompt("Enter your name : ", "your name
here");
alert("You have entered : " + retVal );
//-->
</script>
</head>
Javascript Objects Overview
JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it provides
four basic capabilities to developers:
Encapsulation: the capability to store related information, whether
data or methods, together in an object
Aggregation: the capability to store one object inside of another
object
Inheritance: the capability of a class to rely upon another class (or
number of classes) for some of its properties and methods
Polymorphism: the capability to write one function or method that
works in a variety of different ways
Objects are a peace of data that has property and method. For
example myself sofi as an object has properties such as hair color,
height, weight, mane, age etc,…
Methods are that I do: teaching, driving car, make tutorials, etc
Example
<html> <head> <title> me as objects</title>
<script type="text/javascript">
var teacher = "sofonias Yitagesu";
</script>
</head>
<body>
<script type="text/javascript">
[Link](“our IP1 teacher’s name is : " + teacher + "<br>");
</script> </body> </html>
You have already learned that JavaScript variables are containers for
data values. This code assigns a simple value (Fiat) to a variable
named car:
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named
car:
The values are written as name: value pairs (name and value
separated by a colon). JavaScript objects are containers for named
values.
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
firstName John
lastName Doe
age 50
eyeColor Blue
Real Life Objects, Properties, and Methods
In real life, a car is an object. A car has properties like weight and
color, and methods like start and stop:
All cars have the same properties, but the property values differ from
car to car. All cars have the same methods, but the methods are
performed at different times.
[Link] = propertyValue;
Example:
lastName Doe
age 50
eyeColor Blue
function() {
fullName return [Link] + " " + [Link];
}
The methods are functions that let the object do something or let
something be done to it. There is little difference between a function
and a method, except that a function is a standalone unit of
statements and a method is attached to an object and can be
referenced by the this keyword. Methods are useful for everything
from displaying the contents of the object to the screen to performing
complex mathematical operations on a group of local properties and
parameters. Example:
[Link]("This is test");
User-Defined Objects:
Example 1:
Example
Spaces and line breaks are not important. An object definition can
span multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Accessing Object Properties
You can access object properties in two ways:
[Link]
Or
objectName[propertyName]
Example1
[Link];
Example2
person["lastName"];
Accessing Object Methods
You access an object method with the following syntax:
[Link]()
Example
name = [Link]();
If you access the fullName property, without (), it will return the
function definition:
Example
name = [Link];
Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword "new", the
variable is created as an object:
var x = new String(); // Declares x as a String object
var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code.
Javascript - The Boolean Object
The Boolean object represents two values either "true" or "false".
Syntax:
Syntax:
array_name.length
The for loop in the above code loops through the elements of the array
and display one by one vertically by adding one line break at the end of
each element. The upper limit of the for loop is set to [Link]
value which is in this case equal to 4
The popular way all the cool kids create arrays these days is to use an open
and close bracket. Below is our groceries variable that is initialized to an
empty array:
You have your variable name on the left, and you have a pair of brackets on
the right that initializes this variable as an empty array. This bracket []
approach for creating an array is better known as the array literal notation.
Now, you will commonly want to create an array with some items inside it
from the very beginning. To create these non-empty arrays, place the items
you want inside the brackets and separate them by commas:
<!–
myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";
//-->
</script>
Notice that my groceries array now contains Milk, Eggs, Frosted
Flakes, Salami, and Juice. I just have to reiterate how important the
commas are. Without the commas, you'll just have one giant item
instead. All right, now that you've learned how to declare an array.
Let's look at how you can actually use it to store and work with data.
One of the nice things about arrays is that you not only have easy
access to the array, but you also have easy access to the array
values...similar to highlighting an item in your grocery list:
The only thing you need to know is what the procedure is for
accessing an individual item. Inside an array, each item is assigned a
number starting with zero. In the above example, Milk would be
given the value 0, Eggs the value 1, Frosted Flakes the value 2, and
so on. The formal term for these numbers is called the index value.
groceries[1]
The index value is passed in to your array using square brackets. In
this example, you are referring to the Eggs value because the index
position 1 refers to it. If you passed in a 2, you would return Frosted
Flakes. You can keep passing in a index value until you have no more
values left.
The range of numbers you can use as your index values is one less
than your array's length. The reason is that, your index values start
with a value of 0. If your array only has 5 items, trying to display
grocery[6] or grocery[5] will result in a message of undefined.
Let's go one step further. In most real world scenarios, you will want
to programmatically go through your array as opposed to accessing
each item individually. You can take what I explained in the previous
paragraph and use a for loop to accomplish this:
Notice the range of your loop starts at 0 and ends just one before
your array's full length (as returned by the length property). This
works because, your array index values go from 0 to one short of the
value returned for the array's length. And yes, the length property
returns a count of all the items in your array!
Adding Items to Your Array
Rarely will you leave your array in the state you initialized it in
originally. You will want to add items to it. To add items to your array,
you will use the push method:
[Link]("Cookies");
The push method is called directly on your array, and you pass in the
data you want to add to it. By using the push method, your newly
added data will always find itself at the end of the array.
For example, after running the code on our initial array, you will see
Cookies added to the end of your groceries array:
If you want to add data to the beginning of your array, you use the
unshift method:
[Link]("Bananas");
When data is added to the beginning of your array, the index value
for all of the existing items increases to account for the newly
inserted data:
The reason is that the first item in your array will always have an
index value of 0. This means that the space originally occupied by the
0th item needs to push itself and everything below it out to make
room for the new data.
Both the push and unshift methods, besides adding the elements to
the array when you use them, return the new length of the array as
well:
alert([Link]("cookies")); // returns 6
Not sure why that is useful, but keep it under your hat in case you do
need it.
Removing Items from the Array
To remove an item from the array, you can use the pop or shift
methods. The pop method removes the last item from the array and
returns it:
The shift method does the same thing on the opposite end of the
array. Instead of the last item being removed and returned, the shift
method removes and returns the first item from the array:
When an item is removed from the beginning of the array, the index
positions of all remaining elements is decremented by 1 to fill in the
gap:
Note that, when you are adding items to your array using unshift or
push, the returned value from that method call is the new length of
your array. That is not what happens when you call the pop and shift
methods, though! When you are removing items using shift and pop,
the value returned by the method call is the removed item itself!
Finding Items in the Array
To find items inside your array, you have two built-in methods called
indexOf and lastIndexOf. These methods work by scanning your array
and returning the index position of the matching element.
The indexOf method returns the first occurrence of the item you are
searching for:
alert(resultIndex); // 1
Notice that the resultIndex variable stores the result of calling
indexOf on our groceries array. To use indexOf, I pass in the element I
am looking for along with the index position to start from:
[Link]("eggs",0);
To combine both of these arrays into one array, use the concat
method on the array you want to make bigger and pass the array you
want to merge into it as the argument. What will get returned is a
new array whose contents are both good and bad:
var goodAndBad = [Link](bad);
trace(goodAndBad);
In this example, because the concat method returns a new array, the
goodAndBad variable ends up becoming an array that stores the
results of our concatenation operation. The order of the elements
inside goodAndBad is good first and bad second.
Sorting an Array
The sort() method sorts an array alphabetically:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](); // Sorts the elements of fruits
Imagine that you wanted to sort an array alphabetically before you
wrote the array to the browser. Well, this code has already been
written and can be accessed by using the Array's sort method.
JavaScript Code:
<script type="text/javascript">
<!–
var myArray2= new Array();
myArray2[0] = "Football";
myArray2[1] = "Baseball";
myArray2[2] = "Cricket";
[Link]();
[Link](myArray2[0] + myArray2[1] + myArray2[2]); //--> </script>
Reversing an Array
The reverse() method reverses the elements in an array.
Example
every() Returns true if every element in this array satisfies the provided testing function.
filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
map() Creates a new array with the results of calling a provided function on every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the array.
reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
some() Returns true if at least one element in this array satisfies the provided testing function.
toSource() Represents the source code of an object
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift() Adds one or more elements to the front of an array and returns the new length of the array.
JavaScript: Form Validation
Validating form input with JavaScript is easy to do and can save a lot
of unnecessary calls to the server as all processing is handled by the
web browser. It can prevent people from leaving fields blank, from
entering too little or too much or from using invalid characters.
The regular expression ^[\w ]+$ will fail if the input is empty as it
requires at least one character (because we used + instead of *). The
first test in the example is therefore only necessary in order to
provide a different error message when the input is blank.
The checkForm function tests the form input against our conditions,
returning a value of true if the form is to be submitted (when all tests
have been passed) or false to abort (cancel) the form submission. It's
that simple.
In a real-life situation you will most likely have more fields to check,
and more complicated conditions, but the principle remains the
same. All you need to do is extend the checkForm function to
encompass the new fields and conditions:
<script type="text/javascript">
function checkForm(form) {
if(!condition1) {
[Link]();
return false;
} if(!condition2) {
[Link]();
return false;
You'll see that the all validation scripts presented on this and
subsequent pages adhere to the same basic format.
2. 2. Working with different types of FORM elements
Text/Textarea/Password boxes
[Link]
}
Make sure to always use == for comparisons. If you use = (the
assignment operator) instead then it can take a long time to debug.
and to see if they have different values we just reverse the logic:
If you want to test numeric values (or add or subtract them) then you
first have to convert them from strings to numbers. By default all
form values are accessed as as strings.
Select/Combo/Drop-down boxes
If you define a value for the OPTION elements in your SELECT list,
then .value will return that, while .text will return the text that is
visible in the browser. Here's an example of what this refers to:
<option value="value">text</option>
If you just want to check that an option has been chosen (ie. that the
SELECT box is no longer in it's default state) then you can use:
if([Link] > 0) {
// an option has been selected
} else { // no option selected }
Checkboxes
These really are simple:
[Link]
will return a boolean value (true or false) indicating
whether the checkbox is in a 'checked' state.
function checkForm(form) {
if([Link]) {
} else {
} return false;
Radio buttons
function checkForm(form) {
if(radioValue = checkRadio([Link])) {
return true;
} else {
return false;
}
<!DOCTYPE HTML>
<html><head>
<meta charset="UTF-8">
<title>Login</title>
<script type="text/javascript">
function validate(form){
var userName = [Link];
var password = [Link];
if ([Link] === 0) {
alert("You must enter a username.");
return false;
}
if ([Link] === 0) {
alert("You must enter a password.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Login Form</h1>
<form method="post" action="[Link]"
onsubmit="return validate(this);">
Username: <input type="text" name="Username" size="10"><br>
Password: <input type="password" name="Password" size="10"><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset Form">
</form></body></html>