You are on page 1of 24

ASP and Java Script reference Page 1 of 24

Adding Data to Access Database


To add data to a database table, you need an existing database plus the table to add the
data to. Let us assume that you have Access Database file name FeedBack.mdb in the
same folder as this file with the following table:
tblFeeds
Field Name Data Type Field Size
user_id Autonumber 8
Name Text 45
Comments Text 200<>
To add a data to the table tblFeeds, first we will have to create a form to enter the data
and then open the database and make the connection.
Here is the form to enter the data before adding to the database:

Form Example
<html>
<head>
<title> Adding to database example </title>
<script type="text/javascript">
<!--
function validate()
{
if(document.form.name.value=="")
{
alert("Name is missing");
return false;
}
if(document.form.comments.value.length<8)
{
alert("Not enough comments entered");
return false;
}
else
{
return true;
}
}
//-->
</script>
</head>
<body>
<form name="form" method="post" action="save.asp">
Name: <input type="text" name="name" maxlength="45"> <br>
Comments: <textarea cols="20" rows="8" name="comments"
maxlength="200"> </textarea><br>
<input type="submit" name="Save" value="Submit" onClick="return validate();">
</form>
</body>
</html>
http://www.aspnetcenter.com Page 1 of 24
ASP and Java Script reference Page 2 of 24

Now, you insert the new record to the database using the information provided through
EnterData.asp. Here is the code to do this:
save.asp
<%
Dim Conn
Dim Rs
Dim sql
'Create an ADO connection and recordset object
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
'Set an active connection and select fields from the database
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
sql= "SELECT name, comments FROM tblFeeds;"

'Set the lock and cursor type


Rs.CursorType = 2
Rs.LockType = 3

Rs.Open sql, Conn 'Open the recordset with sql query

Rs.AddNew 'Prepare the database to add a new record and add


Rs.Fields("name") = Request.Form("name")
Rs.Fields("comments") = Request.Form("comments")

Rs.Update 'Save the update


Rs.Close
Set Rs = Nothing
Set Conn = Nothing
%>

The third field (user_no) of our table is auto generated and sequentially will accommulate
it self on each addition of new record.
You redirect the user to another page when the record is added to the database using
<%response.redirect("view.asp")%>

After the data is added to the database, the next thing you may want do is view to see
what is added. The code is very similar.
This code bellow displays the fields.

view.asp
<%
Dim Conn
Dim Rs
Dim sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
http://www.aspnetcenter.com Page 2 of 24
ASP and Java Script reference Page 3 of 24
sql= "SELECT name, comments FROM tblFeeds;"
Rs.Open sql, Conn
Do While not Rs.EOF
Response.Write
("============================================="&"<br>")
Response.Write ("Name: " & "<font color='red'>" & Rs("name") & "</font>")
Response.Write ("<br>")
Response.Write ("Comment: " & "<font color='red'>" & Rs("comments") & "</font>")
Response.Write ("<br>")
Rs.MoveNext
Loop
Rs.Close
Set Rs = Nothing
Set Conn = Nothing
%>

Update a record
There are more than one way to do things. For this example, we are going to list
items from the database so that you can select a record using radio button.
Code to list records from tblFeeds

<html>
<body >
Select name to update.
<%
Dim Conn, Rs, sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
sql= "SELECT * FROM tblFeeds;"
Rs.Open sql, Conn
Response.Write "<FORM name='Update' method='post' action='toUpdateT.asp'>"
Response.Write "<table border=1 cellspacing=0>"
Response.Write "<tr>"&"<td colspan='3' align='center'>"&"Select a comment to update
and click select"&"</td>"&"</tr>"
Response.Write "<tr>"&"<th align='center' colspan='2'>"&"Name"&"</th>"&"<th
align='center'>"&"Comment"&"</th>"&"</tr>"
if NOT Rs.EOF then
Do While not Rs.EOF
Response.Write ("<tr>")
Response.Write ("<td>"&"<input type='radio' name='ID'
value="&Rs("user_id")&">"&"</td>")
Response.Write ("<td>"&Rs("name")&"</td>")
Response.Write ("<td>"&Rs("comments")&"</td>")
Response.Write ("</tr>")
Rs.MoveNext

http://www.aspnetcenter.com Page 3 of 24
ASP and Java Script reference Page 4 of 24
Loop
else
Response.Write("No records found")
end if
Response.Write("<tr>"&"<td colspan='3' align='center'>"&"<input type ='submit'
name='submit' value='Select' >"&"</td>"&"</tr>")
Response.Write "</table>"
Rs.Close
Set Rs = Nothing
Set Conn = Nothing
%>
</form>
</body>
</html>
User_ID is a unique field which identifies the selected record. When the user selects
record and clicks on Select, the information is processed in the toUpdatT.asp file.
toUpdateT.asp file allows the user edit the record

<html>
<body>
<form name="updated" action="updateComment.asp" method="post">
<%
Dim ID, name, comments
ID= Request.Form("ID")
name = Request.Form("name")
comments=Request.Form("comments")
if name="" then
Response.Write "You did not select a name to update!"
Else
Dim Conn, Rs, sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
sql= "Select * FROM tblFeeds WHERE user_id="&ID
Rs.Open sql, Conn
if NOT Rs.EOF then
%>
<table border=1 cellspacing=0>
<tr><td colspan="2" align="center">Update and save</td></tr>
<tr>
<td>Name: </td>
<td><input type="text" name="name" size="30" maxlength="45"
value="<%=Rs("name")%>"></td>
</tr><tr>
<td>Comment: </td>
<td><input type="text" name="comments" size="30" maxlength="250"
value="<%=Rs("comments")%>"></td>
</tr><tr>
http://www.aspnetcenter.com Page 4 of 24
ASP and Java Script reference Page 5 of 24
<td colspan="2" align="center"><input type="submit" name="submit"
value="Save"></td>
</tr>
</table>
</form>
<%
else
Response.Write("Record does not exist")
end if
Conn.Close
Set Conn = Nothing
End If
%>
</body>
</html>

After the new data is entered, the next thing is to save the data and the following is the file
to do that.
updateComment.asp saves the new information

<html>
<body>
<%
Dim name,comments, user_id
ID = Request.Form("ID")
name = Request.Form("name")
comments=Request.Form("comments")
if name="" OR comments="" then
Response.Write "A field was left empty, please try again!"
Else
Dim Conn ,Rs, sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
sql= "Update tblFeeds Set name='"& name & "', comments='" & comments &"' WHERE
user_id=" & ID
Rs.Open sql, Conn
Conn.Close
Set Rs=Nothing
Set Conn = Nothing
Response.Write "Successfully Updated"
End If
%>
</body>
</html>

Delete a record
http://www.aspnetcenter.com Page 5 of 24
ASP and Java Script reference Page 6 of 24
We are going to use two files in order to delete a record. First file (toDelete.asp) is to
view all the records and the second file (deleteComment.asp) is to delete selected
record.
Code to list records from tblFeeds

Select name to delete.


<%
Dim Conn, Rs, sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
sql= "SELECT * FROM tblFeeds;"
Rs.Open sql, Conn
Response.Write "<FORM name='Delete' method='post' action='DeleteComment.asp'>"
Response.Write "<table border=1 cellspacing=0>"
Response.Write "<tr>"&"<td colspan='3' align='center'>"&"Select a comment to delete
and click delete"&"</td>"&"</tr>"
Response.Write "<tr>"&"<th align='center' colspan='2'>"&"Name"&"</th>"&"<th
align='center'>"&"Comment"&"</th>"&"</tr>"
Do While not Rs.EOF
Response.Write ("<tr>")
Response.Write ("<td>"&"<input type='radio' name='ID'
value="&Rs("user_id")&">"&"</td>")
Response.Write ("<td>"&Rs("name")&"</td>")
Response.Write ("<td>"&Rs("comments")&"</td>")
Response.Write ("</tr>")
Rs.MoveNext
Loop
Response.Write("<tr>"&"<td colspan='3' align='center'>"&"<input type ='submit'
name='submit' value='Delete' onClick='return validate();'>"&"</td>"&"</tr>")
Response.Write "</table>"
Response.Write "</form>"
Rs.Close
Set Rs = Nothing
Set Conn = Nothing
%>

The purpose of this file to view records and select one. Selected record is deleted
through deleteComment.asp file.
deleteComment.asp file

<%
Dim ID
ID = Request.Form("ID")
if ID="" then
Response.Write "You did not select a name to delete!"
Else
Dim Conn
http://www.aspnetcenter.com Page 6 of 24
ASP and Java Script reference Page 7 of 24
Dim Rs
Dim sql
Set Conn = Server.CreateObject("ADODB.Connection")
Set Rs = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
sql= "Delete * FROM tblFeeds WHERE user_ID='" & ID
Rs.Open sql, Conn
Conn.Close
Set Conn = Nothing
Response.Write "Successfully Deleted"
End If
%>

Processing forms using ASP


You can process HTML forms using these two powerful ASP objects, Response and
Request. Response outputs the value to a page and Request retrieves values from an
object. Take a look at the following example:

form name=”userForm” method=”post” Result


action=”userForm.asp”>
Enter a user name: <input type=”text” name=”userName”
size=”20”> Enter a user name:
Enter a password: <input type=”password”
name=”password” size=”20”> Enter a password:
<inpute type=”submit” name=”submit” value=”Send”>
</form>
We just created HTML form and tell the browser to process the form using the file
"userForm.asp". The following is userForm.asp file that writes the values from the
form.

<html>
<head>
<title>Process form Info</title>
</head>
<body>
You have typed the user name <%=Request.Form("userName")%> and the password
<%=Request.Form("password")%>.
</body>
</html>

Form Processing Example 2

You can store value retrieved from form into variables in order to use these value
whatever way you want. Take a look these at this example which is little bit more
complex then previous one.

http://www.aspnetcenter.com Page 7 of 24
ASP and Java Script reference Page 8 of 24

<html>
<head>
<title>Form Example 2</title>
</head>
<body>
<p><b>This example process basic form elements</b>
<form method="POST" action="formProcess.asp">
<p>Your name: <input type="text" name="Name" size="20"><br>
Status: <input type="radio" value="Customer" name="status">Customer <input
type="radio" name="status" value="Visitor">Visitor<br>
Do you own any of these trucks:<br>
<input type="checkbox" name="truck" value="Land Cruiser">Land Cruiser<br>
<input type="checkbox" name="truck" value="Sequoia">Sequoia<br>
<input TYPE="checkbox" name="truck" value="4Runner">4Runner<br>
<input TYPE="checkbox" name="truck" value="Highlander">Highlander<br>
<input TYPE="checkbox" name="truck" value="Tundra Access Cab">Tundra Access
Cab<br>
Car of Choice:<select size="1" name="product">
<option value="MR2 Spyder">MR2 Spyder</option>
<option value="Celica">Celica</option>
<option value="Matrix">Matrix</option>
<option value="Avalon">Avalon</option>
<option value="Camry">Camry</option>
<option value="Corolla">Corolla</option>
<option value="Echo">Echo</option>
<option value="Prius">Prius</option>
<option value="RAV4 EV">RAV4 EV</option>
</select><br>
Enter some general comments about what you think about Toyota cars:<br>
<textarea rows="5" name="Comments" cols="50"></textarea><br>
<align="center"><input type="submit" value="Submit" name="submit"><br>
</form>
</body>
</html>
Result of the above code Code for formProcess.asp
<html>
This example process basic form <head>
elements <title>Result of your information</title>
</head>
Your name: <body>
Status: Customer Visitor <%
Do you own any of these trucks: dim name, status, truck, car, comments
Land Cruiser name=Request.Form("Name")
Sequoia status=Request.Form("status")
4Runner car=Request.Form("car")
Highlander comments=Request.Form("comments")
Tundra Access Cab truck=Request.Form("truck")
Car of Choice: %>

http://www.aspnetcenter.com Page 8 of 24
ASP and Java Script reference Page 9 of 24
Your name: <b><%=name%></b><br>
Status: <b><%=status%></b><br>
Your favourite car is: <b><%=car%></b><br>
You currently own these trucks:<b>
Any comments about Toyota cars:
<%=truck%></b><br>
Your comments about Toyota
products:<b><%=comments%></b>
</body>
</html>
Type some information into the form elements and hit submit to see the code in action.

ASP Cookies
A cookie is object used to identify the user by his/her computer. Each time the same
computer access the page, the cookie will also be retrieved if the expiry date has
future value. Creating cookies in asp is very simple. Use Response.Cookie to create
a cookie or Request.Cookie to read a cookie.
The following example creates a cookie named userName and assigns value:
<%
Response.Cookies("userName")="user123"
%>

The example bellow will retrieve the cookie we create above:


<%
user=Request.Cookies("userName")
response.write("Welcome " & user)
%>
The result of the above example will look like this:
welcome user123

The cookie will be deleted after your browser is closed unless you set the expiry date to a
future date.
The following example will keep the cookie in place for 30 days after setup date:

<%
Response.Cookies("userName")="user123"
Response.Expires("userName").Expires = Date + 30
%>

You can also set a cookie with multiple values like the following:

<%
Response.Cookies("user")("userName") = "Bell"
Response.Cookies("user")("firstName") = "Bellion"
Response.Cookies("user")("lastName") = "Briabion"
%>

The above Cookie has Keys. When you want retrieve a cookie with multiple values, you
will have to loop through the values using for loop statement
http://www.aspnetcenter.com Page 9 of 24
ASP and Java Script reference Page 10 of 24

Server Variables
The following example dominstrates how to retrieve some of the usefull server variables.
<%
agent = Request.ServerVariables("http_user_agent") 'Gets the browser type
IP = Request.ServerVariables ("REMOTE_ADDR") 'Retrieves the user IP Address
dnsIP = Request.ServerVariables("remote_host") 'Retrieves the remote host IP Address
serverName = Request.ServerVariables("server_name") 'Retrieves the page domain name
referer = request.servervariables("http_referer") 'Retrieves the referer url
scriptName=request.servervariables("script_name") 'Retrieves current page
serverPort=request.servervariables("server_port") 'Retrieves server port
serverSoftware=request.servervariables("server_software") 'Retrieves server software
Url=request.servervariables("URL") 'Retrieves page url
method=request.servervariables("Request_Method") 'Retrieves request mehtod .. get or post
%>
<%
Response.Write("<b>User Agent: </b>"&agent &"<br>")
Response.Write("<b>IP Address:</b> "&IP &"<br>")
Response.Write("<b>Remote host IP:</b> "&dnsIP &"<br>")
Response.Write("<b>Server Domain name: </b>"&serverName &"<br>")
Response.Write("<b>Referer page:</b> "&referer &"<br>")
Response.Write("<b>Script Name: </b>"&scriptName &"<br>")
Response.Write("<b>Server Port: </b>"&serverPort &"<br>")
Response.Write("<b>Server Sortware:</b> "&serverSoftware &"<br>")
Response.Write("<b>Page url: </b>"&Url &"<br>")
Response.Write("<b>Request Method:</b> "&method &"<br>")
%>

Forms

Java script is used to validate forms, display information in text box or when button
is clicked, and other nice activities. Form validation means checking that proper
information are entered in the form fields before submission. Forms are not of much
use in terms of processing and posting when you are limited to HTML and you don't
have access to other script such as CGI. This discussion is limited to form
validations. If you want learn how create them, check out the html form page.

The following example alerts the value entered the text fields:

<html> The only JavaScript concept of this example


<head> is OnClick. onClick event handler responds
</head> when object is clicked and executes the
<body> JavaScript code or function. In this case, it
<FORM name="fm"> executes alert box . The alert box displays
Type your first name: the values in the text boxes.
<INPUT type="text" name="first"><br> Here is the result of this example:
Type your last name:
<INPUT type="text" name="last"> Type your first name:

http://www.aspnetcenter.com Page 10 of 24
ASP and Java Script reference Page 11 of 24
<INPUT type="button" name="dis" value="Display"
onClick='alert("You say your name is:
"+document.fm.first.value+"
"+document.fm.last.value)'> Type your last name:
</FORM>
</body>
</html>

The following example explains how to select and display:

<html>
<body>
<html>
<body>
We use onChange event handler, to
<FORM name="fm2">
display alert box with the selected
Select one: <select name="selec"
value. OnChange executes the
onchange='alert("You selected
specified JavaScript code or
"+document.fm2.selec.value)'><br>
function on the occurance of a
<option>Select One
change event. In this case, it
<option value="Java">Java
executes an alert box that displays
<option value="C++">C++
selected value of the select box.
<option value="Cobol">Cobol
Here is the result of this example:
</select>
</FORM>
Select one:
</body>
</html>
</body>
</html>

Form Validations

The most practical business use of java script is object validations. Making sure
that the user's information is as it required. This sample is java script code that
checks and alerts if the fields of the form are empty.

<HTML> How it works


<HEAD> We created a function called
<SCRIPT LANGUAGE=JAVASCRIPT> validate which takes a parameter.
function validate(formCheck) //Function with a parameter This parameter represents the form
representing a form name. name.
{ Using if statement, we compare the
if (formCheck.name.value =="") text field name with empty string.
{ If this field is equal to the empty
alert("Please provide your name:"); string, then displayed alert box and
formCheck.name.focus(); set the focus to this field. We then
return false; return false to avoid the action to
} be continued. Email field is slightly
var mail=formCheck.email.value different. For this field, we check if

http://www.aspnetcenter.com Page 11 of 24
ASP and Java Script reference Page 12 of 24
if (mail.indexOf("@.") == -1)
{
alert("Please type a valid email:");
formCheck.email.focus();
return false;
@ and . are provided. If not, we
}
alert the user, set the focus and
return true;
return false.
}
If the two controls pass true value,
</SCRIPT>
then the function returns true. In
</HEAD>
this case, onClick event handler
<BODY>
returns true and nothing happens.
<FORM name="inform" action="" method "post">
Note: If the form action proceeds
Your Name: <INPUT type=text NAME="name"
to another page, use onSubmit
value=""SIZE=20><br>
instead of onClick. onSubmit
Your Eamil: <INPUT type=text NAME="email" value=""
executes the function and continues
SIZE=30><br>
processing the file defined in the
<INPUT type=button name="submit" value=" Send "
form action
onClick = "return validate(inform)"; >
<INPUT type=reset name=reset value=" Clear ">
</FORM>
</BODY>
</HTML>

Window object refers to the browser and all the items you can see within it. This
lecture explains objects to create pop-up window and properties and methods
available. As we all ready explained, properties are sub- objects which is part of
another object and methods are ways to do things. Javascript window object
properties could be some thing like window name, size, address, etc. Javascript
window object methods are things like open, close, scroll, move, resize, alert, etc.
The least you could have for window is open a blank window. Here is how you open
a blank window:

window.open()
This opens blank window and uses all the default settings. The best way to display a
window with particular size, color, menus, toolbars, objects, etc is to create a
function and call it when a linke or object is clicked or onload event.
The following example is pop-up window that displays another web site in smaller
window:

<html> We just created a pop-up window with,


<head> height of 400 pixels wide and width of 650
<SCRIPT LANGUAGE="javascript"> pixels. It displays the web site
function windowE() www.dialtone.com. The name of the
{ window is winE and it will not display a
window.open('http://tek-tips.com/','winE', toolbar because we set the toolbar to no.
'height=400,width=650,toolbar=no') This window is created in function. The only
} thing appears when this page loads is "click

http://www.aspnetcenter.com Page 12 of 24
ASP and Java Script reference Page 13 of 24
</SCRIPT>
</head>
<body> here" in link. This link calls the function that
<A HREF="javascript:windowE()" >Click here</A> creates the window.
</form> Here is the result: Click here
</body>
</html>

The syntax to remember when creating pop-up window is


window.open("url", "windowName", "windowAttributes"). URL you can specify any url,
local or foreign. Without a url, blank window will be display.
WindowName is the name of the object.
WindowAttributes are arguments available such as toolbar, statusbar, scrollbars, etc.
Here are list of attributes you can use to customize your pop-up window:

width height toolbar


location directories status
scrollbars resizable menubar

The following example uses all the attributes listed above:

<html>
<head>
<script type="text/javascript">
function openwindow()
{
window.open("http://www.tek-tips.com/","WinC",
"toolbar=no,location=no,directories=no, Again this window display web site and sets
status=no,menubar=no,scrollbars=no,resizable=no, all attributs to no, which means this window
copyhistory=no,width=400,height=400") will not display any of those named attributes.
} Another thing to note is, we using button to
</script> call the function that creates the window.
</head> Bellow is the result of this example. Click to
<body> view it.
<form>
<input type="button" value="Open
Window"onclick="openwindow()">
</form>
</body>
</html>

The following complete list of properties and methods available for window objects.

Property Description Syntax


Returns boolean value to determine if a
Closed window.closed
window has been closed
Defines the default message displayed in a
defaultStatus window.defaultStatus(="message")
window's status bar
http://www.aspnetcenter.com Page 13 of 24
ASP and Java Script reference Page 14 of 24
Defines the document to displayed in a
document window.document
window
Returns an array containing references to all
frames the named child frames in the current window.frames(="frameId")
window
history Returns the history list of visited URLs window.history
Returns the height of the window's display
innerHeight window.innerHeight = value
area
Returns the width of the window's display
innerWidth window.innerWidth = value
area
length Returns the number of frames in the windowwindow.length
location The URL loaded into the window window.location
Windows location bar. It has the property
locationbar window.locationbar.visible=false
visible.
Windows menu bar. Alos has visible
menubar window.menubar.visible=false
property.
name Sets or returns window's name window.name
The name of the window that opened the
opener window.opener
current window
Returns the height of the outer area of the
outerHeight window.outerHeight
window
Returns the width of the outer area of the
outerWidth window.outerWidth
window
Return the X-coordinate of the current
pageXOffset window.pageXOffset
window
Return the Y-coordinate of the current
pageYOffset window.pageYOffset
window
The name of the window containing this
parent window.parent
particular window
Returns boolean value indicating the
personalbar window.personalbar.visible=false
visibility of the directories bar
Returns boolean value indicating the
Scrollbars window.scrollbars.visible=false
visibility of the scrollbars bar
Self Refers to current window self.method
The message displayed in the window's
Status window.method="message"
status bar
Returns boolean value indicating visibility
Statusbar window.statusbar.visible=false
of the status bar
Returns boolean value indicating visibility
Toolbar window.toolbar.visible=false
of the tool bar
Top Returns the name of topmost window window.top
Window Returns the current window window.[property]or[method]
Method Description Syntax
alert(message) Displays text string on a dialog box alert("Type message here")

http://www.aspnetcenter.com Page 14 of 24
ASP and Java Script reference Page 15 of 24
back() Loads the previous page in the window window.back()
blur() Removes the focus from the window window.blur()
Sets the window to capture all events of a
captureEvents() window.captureEvent(eventType)
specified type
Clears the timeout, set with the setTimeout
clearTimeout() window.clearTimeout(timeoutID)
method
close() Closes the window window.close()
Displays a confirmation dialog box with the
confirm(message) confirm("type message here")
text message
disableExternalCapture/ window.disableExternalCapture( )/
Enables/disables external event capturing
enableExternalCapture window.enableExternalCapture( )
focus() Gives focus to the window window.focus()
forward() Loads the next page in the window window.forward()
Invokes the event handler for the specified
handleEvent(event) window.handleEvent(eventID)
event
moveBy(horizontal, Moves the window by the specified amount
window.moveBy(HorValue, VerValue)
vertical) in the horizontal and vertical direction
This method moves the window's left edge
moveTo(x, y) and top edge to the specified x and y co- moveTo(Xposition,Yposition)
ordinates
open() Opens a window window.open(url, name, attributes)
print() Displays the print dialog box window.print()
prompt(message,defaultV window.prompt("type message
Displays prompt dialog box
alue) here",value)
Release any captured events of the specified
releaseEvents(event) window.releaseEvents(eventType)
type
resizeBy(horizantal,
Resizes the window by the specified amount window.resizeBy(HorVoue,VerValue)
vertical)
Resizes the window to the specified width window.resizeTo(widthValue,heightVal
resizeTo(width,height)
and height ue)
Scrolls the window to the supplied co-
scroll(x, y) window.scroll(xVlue,yValue)
ordinates
Scrolls the window's content area by the
scrollBy(x, y) window.scrollBy(HorVlue,VerValue)
specified number of pixels
Scrolls the window's content area by the
scrollTo(x, y) window.scrollTo(xVlue,yValue)
specified number of cordinates
setInterval(expression, Evaluates the expression every time window.setIntervals(expression,millise
time) milliseconds conds)
stop() Stops the windows from loading window.stop()

Working Example -Order & Credit card validation


Select Pizza Type: Select Toppings:
Extra Cheese
Price Beef
Onion
http://www.aspnetcenter.com Page 15 of 24
ASP and Java Script reference Page 16 of 24
Pineapple
Pepper
Anchovy
Payment Method

Card Number:
Expiration Date:

www.clik.to/program

Close | Home

Note: This code does not check credit card expiry date. Cancelled or not issued credits
cards are still valid and cannot be validated using JavaScript.

<html>
<head>
<script type="text/javascript">
<!----
/* Developed by Abdirahman Sh. Abdisalam @ www.clik.to/program */
function validData()
{
var price =0;
var msg ="";
var toppings =new Array(0);
pizza =document.form.pizzaSize.value;
msg=pizza+" Pizza"+" with ";

if(pizza=="") { alert("No pizza type selected" ); return false; }


else if(pizza=="Small") { price=9.99;}
else if(pizza=="Personal") { price=6.54 }
else if(pizza=="Medium") { price=12.60; }
else if(pizza=="Large") { price=15.80; }
else if(pizza=="Extra Large") { price=19.99;}

for( i=0; i<form.toppin.length;i++)


{
if(form.toppin[i].checked)
{
price+=.50;
toppings.push(form.toppin [i].value);
}
}
for( i=0;i<toppings.length-2;i++)
{
msg=msg+toppings[i]+', ';
}
http://www.aspnetcenter.com Page 16 of 24
ASP and Java Script reference Page 17 of 24
if(toppings.length==1)
{
msg=msg+toppings[0]+' ';
}
if(toppings.length>1)
{
msg=msg+toppings[i]+' and '+toppings[i+1]+' ';
}
if(document.form.paymentMethod.value=="")
{
alert("Please select payment method");
return false;
}
else if(document.form.paymentMethod.value!="Cash")
{
if(!validCreditCard())
{
return false;
}
}
document.form.price.value='$'+price;
document.form.result.value="Your order: "+msg+" Total Price "+'$'+price+" Paid with
"+document.form.paymentMethod.value;
}
//===============Valid credit card======================
function validCreditCard()
{
/* Developed by Abdirahman Sh. Abdisalam @ www.clik.to/program */
cardNumber= document.form.card.value;
if(cardNumber=="")
{
alert("Enter your credit card number");
return false;
}
for(x=0;x<cardNumber.length;x++)
{
if(cardNumber.charCodeAt(x)<48 || cardNumber.charCodeAt(x)>57)
{
alert("Please enter numbers only, no spaces");
return false;
}
}
cardType=document.form.paymentMethod.value;
switch(cardType)
{
case "MasterCard":
if(cardNumber.length!=16 || cardNumber.substr(0,2) <51 || cardNumber.substr(0,2)>55 )
{
alert("Invalid master card number");
return false;
http://www.aspnetcenter.com Page 17 of 24
ASP and Java Script reference Page 18 of 24
}
break;
case "Visa":
if(cardNumber.substr(0,1) !=4)
{ alert("Invalid Visa number");
return false;
}
else if(cardNumber.length!=16 && cardNumber.length!=13)
{
alert("Invalid Visa number");
return false;
}
break;
case "Amex":
if(cardNumber.length !=15)
{
alert("Invalid Amex number");
return false;
}
else if(cardNumber.substr(0,2)!=37 && cardNumber.substr(0,2)!=34)
{
alert("Invalid Visa number");
return false;
}
break;
case "Cash":
return true;
break;
default:
alert("Card type unceptable");
}
if(!CheckValid())
{
/* Developed by Abdirahman Sh. Abdisalam @ www.clik.to/program */
alert("The card is not valid yet, You must enter valid credit card to process. This program validates
any credit card");
return false;
}
return true;
}
function CheckValid()
{
/* Developed by Abdirahman Sh. Abdisalam @ www.clik.to/program */
var cardNumber = document.form.card.value;
var no_digit = cardNumber.length;
var oddoeven = no_digit & 1;
var sum = 0;
for (var count = 0; count < no_digit; count++) {
var digit = parseInt(cardNumber.charAt(count));
if (!((count & 1) ^ oddoeven)) {
http://www.aspnetcenter.com Page 18 of 24
ASP and Java Script reference Page 19 of 24
digit *= 2;
if (digit > 9)
digit -= 9;
}
sum += digit;
}
if (sum % 10 == 0)
return true;
else
return false;
}
//==============Final Execution===============
//----------------------------->
</script>
</head>
<body bgcolor="#999fff">
<form name="form" method="post">
<table width="95%" cellspacing="0" cellpadding="0" border="0" bgcolor="cornsilk">
<tr>
<td><strong>Select Pizza Type:</strong><br><select name="pizzaSize">
<option>
<option value="Personal">Personal<BR>
<option value="Small">Small<br>
<option value="Medium">Medium<br>
<option value="Large">Large<br>
<option value="Extra Large">Extra Large
</select><br>
<strong>Price</strong><br>
<input type="text" name="price" size="8"></td>
<td><strong>Select Toppings:</strong><br><input type="checkbox" name="toppin"
value="Cheese">Extra Cheese<BR>
<input type="checkbox" name="toppin" value="Beef">Beef<br>
<input type="checkbox" name="toppin" value="Onion">Onion<br>
<input type="checkbox" name="toppin" value="Pineapple">Pineapple<br>
<input type="checkbox" name="toppin" value="Pepper">Pepper<br>
<input type="checkbox" name="toppin" value="Anchovy">Anchovy</td>
</tr>
<tr>
<td><strong>Payment Method</strong><br><select name="paymentMethod">
<option>
<option value="Cash">Cash
<option value="MasterCard">MasterCard
<option value="Visa">Visa
<option value="Amex">American Express
</select>
<br>
Card Number: <input name="card" size="16" maxlength="19"><br>
Expiration Date:
<select name="ExpMon">
<option value="1" selected>1
http://www.aspnetcenter.com Page 19 of 24
ASP and Java Script reference Page 20 of 24
<option value="2">2
<option value="3">3
<option value="4">4
<option value="5">5
<option value="6">6
<option value="7">7
<option value="8">8
<option value="9">9
<option value="10">10
<option value="11">11
<option value="12">12
</select>
<select name="ExpYear">
<option value="2003" selected>2003
<option value="2004">2004
<option value="2005">2005
<option value="2006">2006
<option value="2007">2007
<option value="2008">2008
<option value="2009">2009
<option value="2010">2010
<option value="2011">2011
<option value="2012">2012
<option value="2013">2013
<option value="2014">2014
</select><br>
</tr><tr>
<td colspan="2"><center><input type="button" name="order" value="Order" onClick="return
validData();">
<input type="reset" name="rset" value="Clear">
</tr><tr>
<td colspan="2"><textarea name="result" cols="60" rows="8"></textarea>
<br><font color="red">www.clik.to/program</font>
<p><a href="javascript:window.close()"><center>Close this
window</center></a></p></center></td>
</tr>
</table>
</form>
</body>
</html>
Working Example -Validate user & password
User Name:
Password:

<html>
<head>
<script language="javascript">
<!--
/* Author: Abdirahman Sh. Abdisalam
http://www.aspnetcenter.com Page 20 of 24
ASP and Java Script reference Page 21 of 24
@ www.clik.to/program or cliktoprogram@yahoo.com
*/
var invalidChars = "@$!#)(%/~>_<";
function checkPassword()
{
password=document.form.password.value;
user =document.form.user.value;
if(user.length<4)
{
alert("User name must be 4 or more characters");
document.form.user.focus();
return false;
}
else if(password.length<8)
{
alert("Password must be 8 or more characters long");
document.form.password.focus();
return false;
}
for(var i = 0; i < invalidChars.length; i++)
{
if(password.indexOf(invalidChars.charAt(i)) != -1 || user.indexOf(invalidChars.charAt(i))!=-1)
{
alert("Please enter valid characters only such as, 1-9, a-z, A-Z");
return false;
}
}
alert("Right information was provided. User name: "+user+"\n Password: "+password);
}
//-->
</script>
</head>
<body bgcolor="#999fff">
<Strong><center>Working Example -<i>Validate user & password</i></center></strong>
<form name="form">
<table bgcolor="cornsilk">
<tr>
<td><Strong>User Name:</strong></td><td><input type="text" name="user"></td>
</tr><tr>
<td><strong>Password:</strong></td><td><input type="password" name="password"></td>
</tr><tr>
<td colspan="2"><input type="button" name="submit" onClick="return checkPassword();"
value="Enter"></td>
</tr>
</table>
</form>
<center><p><a href="javascript:window.close()"><center>Close</a> | <a href = "#" onClick =
"window.opener.location = 'http://www.clik.to/program'; window.close();">Home</a></p></center>
</body>

http://www.aspnetcenter.com Page 21 of 24
ASP and Java Script reference Page 22 of 24
</html>
Asp code to give every row in ur result list alternate colors
: : : Distributed by Nnabike Okaro nnabike@datastruct.com www.datastruct.com
</TABLE>
<%
'Display results in a table
rs.MoveFirst
'counter for row colors

i=1
Do While rs.Eof = False
'ur code
'change colors
i = cint(i)
val = i mod 2
if val = 1 then color="white" else color="lightgrey" end if
i = i+1

<%
<TR BGCOLOR=<%=color%> bordercolor="LIGHTGREY">
<td> //ur data </td>
</TR>
<%
rs.MoveNext
Loop
Conn.close
%>
</TABLE>

VB Script Form Validation


Form validation involves checking if the required information is provided by the
user. We can make sure to see if a field is empty, figure out type of value provided,
count number of characters or value, can check if special character(s) is present and
more.
Here is a syntax for checking a field value.
if form.name.value="" then msgbox"Please enter name". This checks if the name field is
empty and informs the user.
if len(form.name.value) < 2 or len(form.txtname.value)>50 then msgbox "Too short or
too long". This checks if the lenth of the value provided is less than 2 characters or more
than 50 characters and if so prompts message.

if instr(form.txtemail.value,"@") = 0 then msgbox("Invalid e-mail"). This checks if @ is


present and prompts message if not.
if (Not (IsNumeric(form.txtage.value)) then msgbox"Invalid age". This check if the value
is not numeric and prompts message if so. To check if it's numeric, do not specify NOT
before IsNumeric.
form.txtage.focus

http://www.aspnetcenter.com Page 22 of 24
ASP and Java Script reference Page 23 of 24
. This put focus in the text box, age.
form.txtage.select
. This highlights the text in the text box.

The following example is form that validates provided information before it summits. See
forms to learning how to do forms.

<html> Notice we did not call the sub procedure


<head> onclick() method. We name the command button
<script language = "vbscript"> cmdUserInfo which is the name of the sub
sub cmdUserInfo_OnClick() procedure that has the validation code. This is an
if len(form.txtName.value)<2 or event driven procedure that evaluates it's code
IsNumeric(form.txtName.value)then when the command button is clicked. When the
msgbox("Type a valid name") button is clicked, if statement checks the name
form.txtName.focus field to make sure 2 characters or more is
form.txtName.select entered and the values are not numbers. If the
elseif len(form.txtAge.value) <2 or Not name field is ok, then we do the age field same
IsNumeric(form.txtAge.value) then making sure that two numbers are entered. If the
msgbox("Type a valid age") name, and age field are ok, then we check the
form.txtAge.focus email field to make sure that the @ sign is
form.txtAge.select present. We prompt a proper error message each
elseif form.txtEmail.value="" then time that the condition is not true.
msgbox("Enter a valid email")
form.txtEmail.focus We use table to make the form objects look
form.txtEmail.select friendly. The txt added to the each text field
elseif instr(form.txtEmail.value,"@") = 0 then name and cmd added to the button are standard
msgbox("Type a valid email") naming convention for visual basic.
form.txtEmail.focus Here is the result of this example
else
msgbox"Success!" end if
end sub
</script>
</head>
<BODY>
<form name = "form" method = "post">
<table border="1">
<tr>
<td>Name:</td><td><input type = "text"name =
"txtName"></td>
</tr>
<tr>
<td>Age:</td><td><input type = "text" name = "txtAge"
size="2"></td>
</tr>
<tr>
<td>Email:</td><td><input type = "text"name
="txtEmail"></td>
</tr>
<tr>
<td><input type = "button" name = "cmdUserInfo" value
http://www.aspnetcenter.com Page 23 of 24
ASP and Java Script reference Page 24 of 24
= "Summit"></td>
</tr>
</table>
</form>
</body>
</html>

http://www.aspnetcenter.com Page 24 of 24

You might also like