JAVA SCRIPT

(Home)

Top 3 Resources 
Resource Doc JavaScript
Resource JavaScript.com
Resource Java-Script.net
Quick Reference
Header Declaration Always insert header declaration into header tag area first. Compile and make sure there are no errors in the browser status bar before inserting more code below the header!
Go Back To Previous Page A href="javascript:history.back(-1);"> Back To Previous Page</A>
Header Declaration Reference File instead of code between tags!

<Script Language="Javascript" src="scripts/wml-menu.js"></script>

Code
Header
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<style type="text/css">A:hover { COLOR: #000000; BACKGROUND-COLOR: #bdb76b }
</style>
<script language="Javascript" src="scripts/wml-menu.js"></script>
  <!-- TWO STEPS TO INSTALL CHECK ALL:

1. Copy the coding into the HEAD of your HTML document
2. Add the last code into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "Uncheck All"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "Check All"; }
}
// End -->
</script>
</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<center>
<form name=myform action="" method=post>
<table>
<tr><td>
<b>Your Favorite Scripts & Languages</b><br>
<input type=checkbox name=list value="1">Java<br>
<input type=checkbox name=list value="2">JavaScript<br>
<input type=checkbox name=list value="3">ASP<br>
<input type=checkbox name=list value="4">HTML<br>
<input type=checkbox name=list value="5">SQL<br>
<br> 
<input type=button value="Check All" onClick="this.value=check(this.form.list)"> 
</td></tr>
</table>
</form>
</center>
ADO   AddNew Method
<!-- BeginAddNewJS -->

<%@LANGUAGE="JScript" %>

<!-- Include file for JScript ADO Constants -->

<%// use this meta tag instead of adojavas.inc%>

<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->



<html>



<head>

    <title>Add New Method Example (JScript)</title>

<style>

<!--

body {

   font-family: 'Verdana','Arial','Helvetica',sans-serif;

   BACKGROUND-COLOR:white;

   COLOR:black;

    }

-->

</style>

</head>



<body>

<h1>AddNew Method Example (JScript)</h1>



<%

    if (Request.Form("Addit") == "AddNew")

    {

        // connection and recordset variables

        var Cnxn = Server.CreateObject("ADODB.Connection")

        var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +

            "Initial Catalog='Northwind';Integrated Security='SSPI';";

        var rsEmployee = Server.CreateObject("ADODB.Recordset");

        //record variables

        var FName = String(Request.Form("FirstName"));

        var LName = String(Request.Form("LastName"));

    

        try

        {

            // open connection

            Cnxn.Open(strCnxn)

        

            // open Employee recordset using client-side cursor

            rsEmployee.CursorLocation = adUseClient;

            rsEmployee.Open("Employees", strCnxn, adOpenKeyset, adLockOptimistic, adCmdTable);

    

            rsEmployee.AddNew();

            rsEmployee("FirstName") = FName;

            rsEmployee("LastName") = LName;

            rsEmployee.Update;



            // of course, you would normally do error handling here

            Response.Write("New record added.")

        }

        catch (e)

        {

            Response.Write(e.message);

        }

        finally

        {

            // clean up

            if (rsEmployee.State == adStateOpen)

                rsEmployee.Close;

            if (Cnxn.State == adStateOpen)

                Cnxn.Close;

            rsEmployee = null;

            Cnxn = null;

        }

    }

%>



<form method="post" action="AddNewJS.asp" id=form1 name=form1>

<table>

<tr>

    <td colspan="2">

    <h4>Please enter the record to add:</h4>

    </td>

</tr>

<tr>

    <td>

        First Name:

    </td>

    <td>

        <input name="FirstName" maxLength=20>

    </td>

</tr>

<tr>

    <td>

        Last Name:

    </td>

    <td>

        <input name="LastName" size="30" maxLength=30>

    </td>

</tr>

<tr>

    <td align="right">

        <input type="submit" value="Submit" name="Submit">

    </td>

    <TD align="left">

        <INPUT type="reset" value="Reset" name="Reset">

    </TD>

</tr>

</table>

<INPUT type="hidden" value="AddNew" name="Addit">

</form>

</body>

</HTML>

<!-- EndAddNewJS -->

				
ADO Find Method
<!-- BeginFindJS -->

<%@  Language=JavaScript %>

<%// use this meta tag instead of adojavas.inc%>

<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->



<html>



<head>

<title>ADO Recordset.Find Example</title>

<style>

<!--

BODY {

   font-family: 'Verdana','Arial','Helvetica',sans-serif;

   BACKGROUND-COLOR:white;

   COLOR:black;

    }

.thead {

   background-color: #008080; 

   font-family: 'Verdana','Arial','Helvetica',sans-serif; 

   font-size: x-small;

   color: white;

   }

.thead2 {

   background-color: #800000; 

   font-family: 'Verdana','Arial','Helvetica',sans-serif; 

   font-size: x-small;

   color: white;

   }

.tbody { 

   text-align: center;

   background-color: #f7efde;

   font-family: 'Verdana','Arial','Helvetica',sans-serif; 

   font-size: x-small;

    }

-->

</style>

</head>



<body bgcolor="white">



<h1>ADO Recordset.Find Example</h1>

<%

    // connection and recordset variables

    var Cnxn = Server.CreateObject("ADODB.Connection");

    var strCnxn = "Provider='sqloledb';Data Source=" + Request.ServerVariables("SERVER_NAME") + ";" +

            "Initial Catalog='Northwind';Integrated Security='SSPI';";

    var rsCustomers = Server.CreateObject("ADODB.Recordset");

        // display string

    var strMessage;    

    var strFind;

    

    try

    {

            // open connection

        Cnxn.Open(strCnxn);

    

            //create recordset using object refs

        SQLCustomers = "select * from Customers;";

    

        rsCustomers.ActiveConnection = Cnxn;

        rsCustomers.CursorLocation = adUseClient;

        rsCustomers.CursorType = adOpenKeyset;

        rsCustomers.LockType = adLockOptimistic;

        rsCustomers.Source = SQLCustomers;

    

        rsCustomers.Open();

        rsCustomers.MoveFirst();

    

            //find criteria

        strFind = "CompanyName like 'g%'"

        rsCustomers.Find(strFind);

    

        if (rsCustomers.EOF) {

            Response.Write("No records matched ");

            Response.Write(SQLCustomers & "So cannot make table...");

            Cnxn.Close();

            Response.End();

        } 

        else {

            Response.Write('<table width="100%" border="2">');

            Response.Write('<tr class="thead2">');

            // Put Headings On The Table for each Field Name

            for (thisField = 0; thisField < rsCustomers.Fields.Count; thisField++) {

                fieldObject = rsCustomers.Fields(thisField);

                Response.Write('<th width="' + Math.floor(100 / rsCustomers.Fields.Count) + '%">' + fieldObject.Name + "</th>");

            }

            Response.Write("</tr>");

            

            while (!rsCustomers.EOF) {

                Response.Write('<tr class="tbody">');

                for(thisField=0; thisField<rsCustomers.Fields.Count; thisField++) {

                    fieldObject = rsCustomers.Fields(thisField);

                    strField = fieldObject.Value;

                    if (strField == null)

                        strField = "-Null-";

                    if (strField == "")

                        strField = "";

                    Response.Write("<td>" + strField + "</td>");

                }

                rsCustomers.Find(strFind, 1, adSearchForward)

                Response.Write("</tr>");

            }

            Response.Write("</table>");

        }

    }

    catch (e)

    {

        Response.Write(e.message);

    }

    finally

    {

        // clean up

        if (rsCustomers.State == adStateOpen)

            rsCustomers.Close;

        if (Cnxn.State == adStateOpen)

            Cnxn.Close;

        rsCustomers = null;

        Cnxn = null;

    }

%>



</body>



</html>

<!-- EndFindJS -->

ADO  GetRows Method
'BeginGetRowsVB



    'To integrate this code

    'replace the data source and initial catalog values

    'in the connection string

    

Public Sub Main()

    On Error GoTo ErrorHandler



     ' connection and recordset variables

    Dim rstEmployees As ADODB.Recordset

    Dim Cnxn As ADODB.Connection

    Dim strSQLEmployees As String

    Dim strCnxn As String

    ' array variable

    Dim arrEmployees As Variant

    ' detail variables

    Dim strMessage As String

    Dim intRows As Integer

    Dim intRecord As Integer

    

    ' open connection

    Set Cnxn = New ADODB.Connection

    strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _

        "Initial Catalog='Pubs';Integrated Security='SSPI';"

    Cnxn.Open strCnxn

    

    ' open recordset client-side to enable RecordCount

    Set rstEmployees = New ADODB.Recordset

    strSQLEmployees = "SELECT fName, lName, hire_date FROM Employee ORDER BY lName"

    rstEmployees.Open strSQLEmployees, Cnxn, adOpenStatic, adLockReadOnly, adCmdText

    

    ' get user input for number of rows

    Do

        strMessage = "Enter number of rows to retrieve:"

        intRows = Val(InputBox(strMessage))

        

          ' if bad user input exit the loop

        If intRows <= 0 Then

            MsgBox "Please enter a positive number", vbOKOnly, "Not less than zero!"

        ' if number of requested records is over the total

        ElseIf intRows > rstEmployees.RecordCount Then

            MsgBox "Not enough records in Recordset to retrieve " & intRows & " rows.", _

            vbOKOnly, "Over the available total"

        Else

            Exit Do

        End If

    Loop

    

      ' else put the data in an array and print

    arrEmployees = rstEmployees.GetRows(intRows)

    

    Dim x As Integer, y As Integer

    

    For x = 0 To intRows - 1

        For y = 0 To 2

            Debug.Print arrEmployees(y, x) & " ";

        Next y

        Debug.Print vbCrLf

    Next x

    

    ' clean up

    rstEmployees.Close

    Cnxn.Close

    Set rstEmployees = Nothing

    Set Cnxn = Nothing

    Exit Sub

    

ErrorHandler:

    ' clean up

    If Not rstEmployees Is Nothing Then

        If rstEmployees.State = adStateOpen Then rstEmployees.Close

    End If

    Set rstEmployees = Nothing

    

    If Not Cnxn Is Nothing Then

        If Cnxn.State = adStateOpen Then Cnxn.Close

    End If

    Set Cnxn = Nothing

    

    If Err <> 0 Then

        MsgBox Err.Source & "-->" & Err.Description, , "Error"

    End If

End Sub

'EndGetRowsVB



ADO Recordset
<SCRIPT LANGUAGE=JAVASCRIPT>

<!--

var conn = new ActiveXObject("ADODB.Connection") ;

var connectionstring = "Provider=sqloledb; Data Source=itdev; Initial Catalog=pubs; User ID=sa;Password=yourpassword"

conn.Open(connectionstring)

var rs = new ActiveXObject("ADODB.Recordset")

rs.Open("SELECT gif, description, page, location FROM menu1", conn)

// Be aware that I am selecting from thi

//     s table, but you need to pick your own t

//     able

while(!rs.eof)

    {
    alert(rs(0));
    rs.movenext

    }   

     rs.close

    conn.close     

    //-->

    </SCRIPT>

  <!-- TWO STEPS TO INSTALL COOKIE - FAVORITE BACKGROUND COLOR:

1. Paste the designated coding into the HEAD of your HTML document 
2. Put the last script into the BODY of your HTML document -->

<!-- STEP ONE: Copy this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE = "JavaScript">
<!-- Begin
var expDays = 30;
var exp = new Date(); 
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function color(){
var favColor = GetCookie('color');
if (favColor == null) {
favColor = prompt("What is your favorite background color?");
SetCookie('color', favColor, exp);
}
document.bgColor=favColor;
return favColor;
}
function set(){
favColor = prompt("What is your favorite background color?");
SetCookie ('color', favColor, exp);
}
function getCookieVal (offset) { 
var endstr = document.cookie.indexOf (";", offset); 
if (endstr == -1) 
endstr = document.cookie.length; 
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) { 
var arg = name + "="; 
var alen = arg.length; 
var clen = document.cookie.length; 
var i = 0; 
while (i < clen) { 
var j = i + alen; 
if (document.cookie.substring(i, j) == arg) 
return getCookieVal (j); 
i = document.cookie.indexOf(" ", i) + 1; 
if (i == 0) break; 

return null;
}
function SetCookie (name, value) { 
var argv = SetCookie.arguments; 
var argc = SetCookie.arguments.length; 
var expires = (argc > 2) ? argv[2] : null; 
var path = (argc > 3) ? argv[3] : null; 
var domain = (argc > 4) ? argv[4] : null; 
var secure = (argc > 5) ? argv[5] : false; 
document.cookie = name + "=" + escape (value) + 
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
((path == null) ? "" : ("; path=" + path)) + 
((domain == null) ? "" : ("; domain=" + domain)) + 
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) { 
var exp = new Date(); 
exp.setTime (exp.getTime() - 1); 
var cval = GetCookie (name); 
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
// End -->
</SCRIPT>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<SCRIPT>
document.write('your favorite background color is : ' + color());
</SCRIPT><br>
<a href="JavaScript:set()">Change background color</a>
</textarea><br></td></tr>
</table>
</form>

<p><center>
  <!-- ONE STEP TO INSTALL ALERT BUTTON:

1. Paste the coding into the BODY of the HTML document -->

<!-- STEP ONE: Copy this code into the BODY of your HTML document -->

<BODY>

<CENTER>
<FORM>

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<INPUT TYPE="button" VALUE="Click here to be alerted" 
onClick='alert("There. You have been alerted.")'>
</FORM>
</CENTER>
SetFocus Friend Sub SetFocus(ByVal MyPage As System.Web.UI.Page, ByVal control As System.Web.UI.Control)
Dim script As String = ""
script = "<SCRIPT languange='JavaScript'>" & "document.getElementById('" & control.ID & "').focus();" & "</SCRIPT>"
MyPage.RegisterStartupScript("sample_focus", script)
End Sub
MsgBox Friend Sub MsgBox(ByVal MyPage As System.Web.UI.Page, ByVal Message As String)
Dim script As String = ""
script = "<SCRIPT languange='JavaScript'>" & "alert('" & Message & "');" & "</SCRIPT>"
MyPage.RegisterStartupScript("sample_focus", script)
End Sub
SectionImage Function var currentPageImage = null;

function setCurrentPageImage() {
if(currentPageImage == null) {
// Set to non-menu pages
if(getCurrentPage() == "WebMenu.aspx") { 
currentPageImage = "./images/WML_Main_Menu.gif";
} else if(getCurrentPage() == "WebLogin.aspx") {
currentPageImage = "./images/WML_Main_Login.gif";
} else if(getCurrentPage() == "WebMgrApproval.aspx") {
currentPageImage = "./images/WML_Mgr_Approval.gif";
} else if(getCurrentPage() == "WebProxy.aspx") {
currentPageImage = "./images/WML_Main_Proxy.gif"; 
} else if(getCurrentPage() == "WebMR_New.aspx") {
currentPageImage = "./images/WML_Main_NewMod.gif"; 
} else if(getCurrentPage() == "WebLast_Mr.aspx") {
currentPageImage = "./images/WML_Main_NewMod.gif"; 
} else if(getCurrentPage() == "WebMR_Open.aspx") {
currentPageImage = "./images/WML_Main_NewMod.gif"; 
} else if(getCurrentPage() == "WebStatus.aspx") {
currentPageImage = "./images/WML_Status.gif"; 
} else {
currentPageImage = "./images/WML_Main_Menu.gif";
}
}
}

function getCurrentPage() {
var currentPage = null;
var urlStr = document.URL; // Current URL on page 
var onlineStart = "/";
var offlineStart = "\\";

// Get last index of seperator
var start = urlStr.lastIndexOf(onlineStart); 

// Test if page ends with HTML
//var isHTML = (urlStr.lastIndexOf(".aspx") != -1) ? true : false;

//alert(isHTML);
//alert(document.URL);

if(start != -1) {
// Set current page
currentPage = urlStr.substring(start+1);
//alert(currentPage); 
} else {
// Not a valid page forward to homepage
currentPage = "WebMenu.aspx";

//alert(currentPage);
return currentPage;
}


//function setSectionImage() {document.sectionImage.src = "images/about_red_header.gif";}
function setSectionImage() {setCurrentPageImage();document.sectionImage.src = currentPageImage;}
  <!-- TWO STEPS TO INSTALL BUTTON LINK:

1. Copy the coding into the HEAD of your HTML document
2. Add the last code into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function goToURL() { window.location = "http://javascript.internet.com/new"; }
// End -->
</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<form>
<input type=button value="New JavaScripts" onClick="goToURL()">
</form>