Beruflich Dokumente
Kultur Dokumente
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;"
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
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
%>
<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>
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 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:
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>
<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.
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:
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>
<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.
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()
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 ";
<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>
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.
http://www.aspnetcenter.com Page 24 of 24