TechiWarehouse.Com


Top 3 Products & Services

1.
2.
3.

Dated: Aug. 12, 2004

Related Categories

JavaScript Programming

In Part1 Introduction and Part 2 The Language we learn about the history of JavaScript and the basic language structure and syntax. Now we shall look at what JavaScript can do, how it can be used to enhance the web experience. In this part we shall look at some of the tasks a JavaScript has to deal with on a regular basis. Let us begin with a simple Sum

A Simple Sum

<html>
<head> 
<script language="JavaScript">
<!--
function do_addition()
{
var num1, num2;
num1=document.Form1.first.value;
num2=document.Form1.second.value;
result=parseFloat(num1)+parseFloat(num2);
document.Form1.Answer.value=result;
}
//-->
</script>
</head>
<body>
<form name="Form1">
First Number:
<input type="text" name="first" size="20"><br>
Second Number:
<input type="text" name="second" size="20"><br>
<input type="button" value="Add" name="add" 
onClick="do_addition()"><br><br>
Answer:
<input type="text" name="Answer" size="20">
</form>
</body>
</html>

All values that are entered in the text elements of an HTML form are taken as strings so we use the parseFloat () function to get the floating point value of the number entered. If you have tried entering strings you will see that the out appears as NaN. NaN stands for Not a Number. In our case ParseFloat () returns NaN when the argument supplied is not a number.

Background Color

<html>
<head>
<title>Changing the background colour
(bgColor) wiht Javascript</title>
</head>
<body bgcolor="#FFFFFF">
<a href="#" onclick=document.bgColor="red">red</a><br>
<a href="#" onclick=document.bgColor="blue">blue</a><br>
<a href="#" onclick=document.bgColor="green">green</a><br>
<a href="#" onclick=document.bgColor="yellow">yellow</a><br>
<a href="#" onclick=document.bgColor="white">white</a><br>
</body>
</html>

Now let us make give this an added functionality. The user can have the background color of his choice

<html>
<head>
<title>Changing the background colour
(bgColor) with Javascript</title> 
</head>
<body bgcolor="#FFFFFF">
<form name="Form1">
enter color (RRGGBB) :
<input type="text" name="color" size="10"><br>
<input type="button" value ="change color"
onClick="document.bgColor=document.Form1.color.value">
</body>
</html>


A Form Based Clock

Having looked at the background color example. Let us make a form based clock that displays time in the 24 hour format. We use the Date() object to get the hours, minutes, seconds of the day. setTimeoiut() evaluates an expression or calls a function after a certain amount of time, specified in milliseconds. We use setTimeout() to call the update() function every one second. So the clock in the text element is updated every second.

<form name="Form1">
<input type="text" size="8" name="Clock">
</form>
<script>
function update()
{
var today=new Date();
var hours=today.getHours();
var minutes=today.getMinutes();
var seconds=today.getSeconds();
if (hours<10)
hours="0"+hours;
if (minutes<10)
minutes="0"+minutes;
if (seconds<10)
seconds="0"+seconds;
document.Form1.Clock.value=hours+":"+minutes+":"+seconds;
setTimeout("update()",1000);
}
update();
</script>

Simply A New Window

Open new window

OpenNewWindow() gets into action when the link is clicked. This function is placed in the head section,JavaScript Tutorial Part III - Common Scripts it basically uses window.open() to open a new window. The document opened is "1.htm" it is called "NewWindow" (this is name given to it and can be used later to communicate with this window). The window is resizable and has a height and a width of 250. We add "return false;" to tell Javascript not to continue with the action that it was doing (going to the URL # - top of this page). If we had put "return true;" you would find yourself reading the contents on top of this page. You should read the Javascript reference to see what are the various other properties that can also be set. By default all properties are is set to "no" or "0", to change this we have to add it in the script. All of the following statements will turn on the toolbar and turn off the rest of the properties

open("new.htm", "MyWindow", "toolbar");
open("new.htm", "MyWindow", "toolbar=yes");
open("new.htm", "MyWindow", "toolbar=1") ;

<html>
<head>
<script language="JavaScript">
<!--
function OpenNewWindow1()
{ 
window.open("1.htm", "NewWindow",
"resizable,height=250,width=250");
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="OpenNewWindow1();return false;">
Open New Window</a></p> 
</body>
</html> 

Simply A New Window With Close

Open new window with close button

In this case we open a window as demonstrated earlier, as the document to be opened in the new window is not specified. Javascript opens a blank window. So can write to the window. You will notice that the window opens with only the menubar and it is not resizable. This is because only the menubar property was mentioned in the window.open() statement. Remember that by default all properties are set to "false". Once the window is opened we output the HTML content. At the end we add a button with the mouse event onClick(), when this event is triggered (The button is clicked upon) window.close() closes the window. That's all there is to simply opening and closing windows.

 
function OpenNewWindow2()
{
MyWindow=window.open("", "displayWindow",
"menubar,height=80,width=250");
MyWindow.document.write(
"<head><title>My window</title></head>");
MyWindow.document.write("<h1>Click to close<h1>");
MyWindow.document.write('<input type="button" value="Close" 
onClick="window.close(); return false;">');
}

Alerts, Confirms, Prompts

Alert, Confirm, Prompt

The above three links should give you an idea about Alerts, Confirms and Prompts. Now let us look at each one in more detail. An alert is simply alerts the user of something, it is very simple to use. We shall be using alerts in our next working example - Form Validation.

<a href="#" onMouseover="alert('That was fast'); return 
false;">Alert,</a>

We use onClick() to trigger the function MyConfirm that is shown below

 
function MyConfirm()
{
if (confirm("Ok/Cancel"))
document.Form2.messagebox.value="ok";
else
document.Form2.messagebox.value="cancel";
return false;
}

For the prompt we use the following function. A default value "this is cool" contained by the variable message is always displayed by the prompt.

 
function MyPrompt()
{
var message = "this is cool";
message = prompt("enter a string", message);
document.Form2.messagebox.value=message;
return false;
}

Form Validation - Another Simple Sum

Coming to the final part of our journey through Javascript. Very often a web designer/programmer needs to take info from the users. An HTML form is the ideal tool to get such data. But the data being entered by the user needs to be verified. All important data MUST be verified on the server, but we could speed up the process of data-entry for the user by providing client-side form validation. This also lessens the load on the server. In order to warn the user if the data is valid we will make use of alert boxes. Try the example below and read on to for a brief explanation on the script.

<html>
<head>
<script language="JavaScript">
<!--function validate_string(str){
while (str.indexOf("  ") != -1) 
str = str.replace("  ", " ");
// removing all extra spaces from the
// stringif (str =="" || str == " ")  return false;}
function validate_integer(num,max,min)
{
n = parseFloat(num);
if (isNaN(n))
return false;
else if (n>max || n<min) 
return false;
}
function validate_email(str)
{
l = str.length;
at=str.indexOf("@");
lastdot = str.lastIndexOf(".");
if (at < 1 || (lastdot > l-3) || (lastdot-at < 2)) 
return false;
}
function validate_form(form)
{
if (validate_string(form.elements[0].value) ==false)
{
alert("Invalid name");
form.elements[0].focus();
return false;
}
// max age is set to 120 and min to 0
if (validate_integer(form.elements[1].value,121,1) ==false)
{
alert("Invalid age");
form.elements[1].focus();
return false;
}
if (validate_email(form.elements[2].value) ==false)
{
alert("Invalid email address");
form.elements[2].focus();
return false;
}
return true;
}
//-->
</script>
</head>
<body>
<form name="Form1" onSubmit="if (validate_form(Form1)==false) 
return false; else return true;">
Name: <input type="text" name="name" size="20"><br>
Age: <input type="text" name="age" size="20"><br>
Email: <input type="text" name="email" size="20"><br>
<input type="Submit" value="Submit" name="submit"><br><br>
</form>
</body>
</html>


Let us begin by looking at the <form> tag. We have used the event onSubmit() that is triggered when the form is submitted. Here we can see that if the form is not validated (if (validate_form(Form1) ==false)) we don't submit the form (return false), but if it is validated we continue submitting the form. Now let us have a look at validate_form(), the elements array is used to refer to the 3 text elements in our form. This function calls validate_string(), validate_integer() and validate_email() and checks if name, age and email are seemingly valid entries.

That's all from us for now. Good luck to you all budding javascripters. I hope this short discussion was beneficial. Take care and happy javascripting.

Return to the top of the page.

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!


Previous Article

Next Article


Fikadu's Comment
Purely to follow up on the utpdae of this topic on your site and would like to let you know just how much I liked the time you took to create this beneficial post. In the post, you spoke on how to truly handle this challenge with all ease. It would be my own pleasure to build up some more tips from your web page and come up to offer other folks what I learned from you. Thanks for your usual terrific effort.
11 Sat Aug 2012
Admin's Reply:

Heartfelt Thanks Fikadu...simply send your tips to us using our contact form. Much Appreciated!




Tarkan's Comment
Can I just say what a relief to find smenooe who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.
23 Mon Apr 2012
Admin's Reply:

Thanks Tarkan




preet's Comment
its gud thanx
28 Wed Jul 2010
Admin's Reply:

You're Welcome






Facebook