Simple validation with Javascript using an html submit button
Sometimes you may wish to validate data before it is submitted to an asp page on the server. This may be to test if a field has been correctly filled in or not, or if a value is between certain limits.
To do this you can use Javascript to test the values on the client PC. If the values are correct, then the form is submitted to the server, if not, then a Javascript message is displayed. The advantage with this method is that the data is validated before it is posted to the server, hence it is quicker and there is less processing to be done on the server.
It is straight forward to add in new fields and to create more complex validation.
<HEAD>
<script language="javascript">
<!--
function send_onclick(frmName) {
var bolSubmit;
bolSubmit = true;
if (frmName.email.value == "") {
alert("You must enter an email address");
bolSubmit = false;
}
if (bolSubmit == true) {
frmName.submit(frmName);
}
}
//-->
</script>
</HEAD>
<BODY>
<form name="frmName" method="post" action="validate.asp">
Enter your name in the text box. If nothing is entered, a warning <br>
message will be displayed. Only when you enter something into the <br>
text box will the page be submitted. <br><br>
Please enter your name : <INPUT TYPE="TEXT" name="email" size="20"><br>
<INPUT TYPE="button" name="butSent" value="Do it" language="javascript" onclick="return send_onclick(frmName)">
</form>
<%if Request.Form("email") <> "" then
Response.Write "Name : " & Request.Form ("email")
end if
%>
</BODY>
</HTML>
Try it by clicking here.
The source code for this tutorial is free to download and is available by clicking here.
A Javascript Back button
To move back, we use the Javascript history function.
Here is the HTML code to put into the body of the web page :
<INPUT TYPE="Button" value="Back" name="butback" language="javascript" onclick="history.back(-2)">
A Javascript Close button
To close a window, use the Javascript window.close() function.
Here is the HTML code to put into the body of the web page :
<INPUT TYPE="Button" value="Close" name="butclose" language="javascript" onclick="window.close()">
A Javascript Open Window button
To open a new window using a button use the following HTML code in your web page :
<INPUT TYPE="Button" value="Open" name="butopen" language="javascript" onclick="window.open('nameofpage', 'newwin', 'height=200,width=200')>
To print
To open the printing dialog box from Javascript, use the following HTML code in your web page :
<a href="Javascript:self.print()">Print</a>