5. Sample Script
Functions: Scripts are written using a function. A function is a block of code that aims to
perform a set of related actions.
Syntax:
function function_name()
{
Script code goes here
}
The keyword “function” should be in lower case
Functions are written between the <script> </script> tags
<script language="javascript" type="text/javascript">
function function_name()
{
Script code goes here
}
function function name()
{
Script code goes here
}
</script>
6. Variables
Variables are containers that hold values. You can declare variables
and store values in them
Declare variable:
var fullname;
Assign value to variable:
fullname=“Tom”;
Declare and assign value to a variable:
var fullname=“Tom”;
The length of a variable can be obtained by the length property:
len=fullname.length;
7. Associating a Function with an Event
A function is called by associating the function with the event handler
of the object.
Example:
<input type="submit" value="Submit" name="submit"
onclick="checkValues()">
The function in the script tag:
<script language="javascript" type="text/javascript">
function checkValues()
{
// some code goes here
}
</script>
8. Script for function checkvalues()
<script language="javascript" type="text/javascript">
function checkValues()
{
var fullnametxt;
var fullnamelength;
fullnametxt=document.myForm.name.value;
if(fullnametxt=="")
{
var error="Please enter your name";
alert(error);
document.myForm.name.focus;
}
}
</script>
9. Associate function with an event
<input type="submit" value="Submit" name="submit"
onclick="checkValues()">
11. Refine the Script
<script language="javascript" type="text/javascript">
function checkValues()
{
var fullnametxt;
var fullnamelength;
fullnametxt=document.myForm.name.value;
if(fullnametxt=="")
{
var error="Please enter your name";
alert(error);
document.myForm.name.focus;
}
else
{
alert("hello "+fullnametxt);
}
}
</script>