Anda di halaman 1dari 24

ASP and Java Script reference Page 1 of 1

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>

http://www.aspnetcenter.com Page 1 of 1
ASP and Java Script reference Page 2 of 2
</body>
</html>

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")
http://www.aspnetcenter.com Page 2 of 2
ASP and Java Script reference Page 3 of 3
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" &
Server.MapPath("FeedBack.mdb")
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>")
http://www.aspnetcenter.com Page 3 of 3
ASP and Java Script reference Page 4 of 4
Response.Write ("</tr>")
Rs.MoveNext
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>

http://www.aspnetcenter.com Page 4 of 4
ASP and Java Script reference Page 5 of 5
<td><input type="text" name="comments" size="30" maxlength="250"
value="<%=Rs("comments")%>"></td>
</tr><tr>
<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
%>

http://www.aspnetcenter.com Page 5 of 5
ASP and Java Script reference Page 6 of 6
</body>
</html>

Delete a record
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

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

<%
Dim ID
ID = Request.Form("ID")
if ID="" then
Response.Write "You did not select a name to delete!"
Else
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")
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:

Result
form name=”userForm” method=”post”
action=”userForm.asp”>
Enter a user name: <input type=”text” name=”userName” Enter a user name:
size=”20”>
Enter a password: <input type=”password” Enter a password:
name=”password” size=”20”>
<inpute type=”submit” name=”submit” value=”Send”>
</form> Send

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
http://www.aspnetcenter.com Page 7 of 7
ASP and Java Script reference Page 8 of 8
<%=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.

<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>
Code for formProcess.asp
Result of the above code
<html>
<head>
This example process basic form
<title>Result of your information</title>
elements
http://www.aspnetcenter.com Page 8 of 8
ASP and Java Script reference Page 9 of 9
elements </head>
<body>
<%
Your name:
dim name, status, truck, car, comments
Status: Customer Visitor name=Request.Form("Name")
Do you own any of these trucks: status=Request.Form("status")
car=Request.Form("car")
Land Cruiser
comments=Request.Form("comments")
Sequoia truck=Request.Form("truck")
%>
4Runner
Your name: <b><%=name%></b><br>
Highlander Status: <b><%=status%></b><br>
Your favourite car is: <b><%=car%></b><br>
Tundra Access Cab
You currently own these trucks:<b>
MR2 Spyder
Car of Choice: <%=truck%></b><br>
Any comments about Toyota cars: Your comments about Toyota
products:<b><%=comments%></b>
</body>
</html>

Submit

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

http://www.aspnetcenter.com Page 9 of 9
ASP and Java Script reference Page 10 of 10
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

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

http://www.aspnetcenter.com Page 10 of 10
ASP and Java Script reference Page 11 of 11
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>
<head>
</head> The only JavaScript concept of this
<body> example is OnClick. onClick event handler
<FORM name="fm"> responds when object is clicked and
Type your first name: executes the JavaScript code or function. In
<INPUT type="text" name="first"><br> this case, it executes alert box . The alert
Type your last name: box displays the values in the text boxes.
<INPUT type="text" name="last"> Here is the result of this example:
<INPUT type="button" name="dis" value="Display"
onClick='alert("You say your name is:
"+document.fm.first.value+" Type your first name:
"+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,
<FORM name="fm2"> to display alert box with the
Select one: <select name="selec" selected value. OnChange executes
onchange='alert("You selected the 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:
Select One
</body>
</html>
</body>
</html>

http://www.aspnetcenter.com Page 11 of 11
ASP and Java Script reference Page 12 of 12
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>
<HEAD>
<SCRIPT LANGUAGE=JAVASCRIPT>
function validate(formCheck) //Function with a parameter
representing a form name.
How it works
{
We created a function called
if (formCheck.name.value =="")
validate which takes a parameter.
{
This parameter represents the form
alert("Please provide your name:");
name.
formCheck.name.focus();
Using if statement, we compare
return false;
the text field name with empty
}
string. If this field is equal to the
var mail=formCheck.email.value
empty string, then displayed alert
if (mail.indexOf("@.") == -1)
box and set the focus to this field.
{
We then return false to avoid the
alert("Please type a valid email:");
action to be continued. Email field
formCheck.email.focus();
is slightly different. For this field,
return false;
we check if @ and . are provided.
}
If not, we alert the user, set the
return true;
focus and 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
SIZE=30><br>
continues processing the file
<INPUT type=button name="submit" value=" Send "
defined in the 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
http://www.aspnetcenter.com Page 12 of 12
ASP and Java Script reference Page 13 of 13
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>
<head>
<SCRIPT LANGUAGE="javascript"> We just created a pop-up window with,
function windowE() height of 400 pixels wide and width of 650
{ pixels. It displays the web site
window.open('http://tek-tips.com/','winE', www.dialtone.com. The name of the
'height=400,width=650,toolbar=no') window is winE and it will not display a
} toolbar because we set the toolbar to no.
</SCRIPT> This window is created in function. The
</head> only thing appears when this page loads is
<body> "click here" in link. This link calls the
<A HREF="javascript:windowE()" >Click here</A> function that 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> Again this window display web site and sets


<head> all attributs to no, which means this window
<script type="text/javascript"> will not display any of those named
function openwindow() attributes. Another thing to note is, we using
{ button to call the function that creates the
window.open("http://www.tek-tips.com/","WinC", window.
"toolbar=no,location=no,directories=no, Bellow is the result of this example. Click to
status=no,menubar=no,scrollbars=no,resizable=no, view it.
copyhistory=no,width=400,height=400")
http://www.aspnetcenter.com Page 13 of 13
ASP and Java Script reference Page 14 of 14
copyhistory=no,width=400,height=400")
}
</script>
</head>
<body>
<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
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
Returns the number of frames in the
length window.length
window
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

http://www.aspnetcenter.com Page 14 of 14
ASP and Java Script reference Page 15 of 15
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")
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,
vertical) in the horizontal and vertical direction VerValue)
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)
resizeTo(width,height) Resizes the window to the specified width window.resizeTo(widthValue,heightV

http://www.aspnetcenter.com Page 15 of 15
ASP and Java Script reference Page 16 of 16
and height alue)
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,millis
time) milliseconds econds)
stop() Stops the windows from loading window.stop()

Working Example -Order & Credit card validation


Select Toppings:
Extra Cheese
Select Pizza Type: Beef
Personal
Onion
Price
$8.04 Pineapple
Pepper
Anchovy
Payment Method
Cash

Card Number:
3 2006
Expiration Date:
Clear

Your order: Personal Pizza w ith Cheese, Pineapple and Peppe


Total Price $8.04 Paid w ith Cash

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">
http://www.aspnetcenter.com Page 16 of 16
ASP and Java Script reference Page 17 of 17
<!----
/* 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]+', ';
}
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;
}
}

http://www.aspnetcenter.com Page 17 of 17
ASP and Java Script reference Page 18 of 18
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;
}
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;
}

http://www.aspnetcenter.com Page 18 of 18
ASP and Java Script reference Page 19 of 19
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)) {
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">

http://www.aspnetcenter.com Page 19 of 19
ASP and Java Script reference Page 20 of 20
<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
<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

http://www.aspnetcenter.com Page 20 of 20
ASP and Java Script reference Page 21 of 21
<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
@ 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)
{
http://www.aspnetcenter.com Page 21 of 21
ASP and Java Script reference Page 22 of 22
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>
</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

http://www.aspnetcenter.com Page 22 of 22
ASP and Java Script reference Page 23 of 23
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
. 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
<script language = "vbscript"> button cmdUserInfo which is the name of the
sub cmdUserInfo_OnClick() sub procedure that has the validation code. This
if len(form.txtName.value)<2 or is an event driven procedure that evaluates it's
IsNumeric(form.txtName.value)then code when the command button is clicked.

http://www.aspnetcenter.com Page 23 of 23
ASP and Java Script reference Page 24 of 24
msgbox("Type a valid name") When the button is clicked, if statement checks
form.txtName.focus the name field to make sure 2 characters or
form.txtName.select more is entered and the values are not numbers.
elseif len(form.txtAge.value) <2 or Not If the name field is ok, then we do the age field
IsNumeric(form.txtAge.value) then same making sure that two numbers are entered.
msgbox("Type a valid age") If the name, and age field are ok, then we check
form.txtAge.focus the 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
Name:
end sub
</script> Age:
</head>
<BODY> Email:
<form name = "form" method = "post"> reset Submit
<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
= "Summit"></td>
</tr>
</table>
</form>
</body>
</html>

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

Anda mungkin juga menyukai