asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Creating Dynamic JavaScript with ASP and Databases
By Travis Giggy
Rating: 3.5 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    Years ago a friend of mine asked me to help him start a new Web site called Carryout.Com. After months of working with data structures of a size I had never seen before, I turned out a decent Web site and an administration site I thought were perfect. An hour after taking a look at the new site, my friend said there was only one small problem.

    "I thought it was perfect," I said.

    "It is," he said. "But I don’t like the way we input restaurant menus."

    "I like it," I replied. "It says ‘Internet’ to me."

    "It says ‘difficult’ to me. Make something else."

    So I proceeded to rack my brain day in and day out (mothers were covering their children’s ears and the kids were saying, "What kind of Web page did he say that was?") until I discovered dynamic JavaScript with ASP and data queries. The following offers an example of dynamic JavaScript for text boxes, radio buttons, and multiselect boxes.

    Example

    Few people realize that you can put ASP tags inside of JavaScript blocks. The following ASP code:

    
    <script language="JavaScript">
    <!--
    	<% for i = 0 to 3 %>
    		form[<%= i %>].element = "<%= i %>"
    	<% next %>
    //-->
    </script>
    
    
    will produce this code in the browser:
    
    <script language="JavaScript">
    <!--
    
    	form[0].element = "0"
    
    	form[1].element = "1"
    
    	form[2].element = "2"
    
    	form[3].element = "3"
    
    //-->
    </script>
    
    
    Once I learned to do this, a small light bulb turned on. The possibilites are endless. You can fit a whole lot of data into one form, on one page. I'm sure everyone who's worked with JavaScript has seen the following example that can be found in the download source in this file article_1_source.htm.

    This was created easily enough by querying the database for some restaurants, looping through the recordset, and writing some static JavaScript to populate the text field with the "text" object of the select box. Here's the code:

    
    <form name="javaRestaurant">
    <%	'open the data connection %>
    <!--#include file="../_include/opendatabase.asp"-->
    <%	dim arrRestaurant
    'SQL query to the database...
    SQL = "select distinct irestaurantid, vchrestaurantname " _
    	& "from restaurant  " _
    	& "where vchcity like 's%'"
    	%><!--#include file="../_include/runsql.asp"--><%
    if not rs.eof then
    	'if not end of file then read all Id
    s and restaurants into an array . . .
    	'	 . . . there are many ways to get and read back data,
    	'but this is my favorite . . .
    	arrRestaurant = rs.getrows(,,array(0,1))
    	arrRestaurant_count = UBound(arrRestaurant,2)
    else
    	'if no rows are returned, set this variable to -1
    	'so the for loop doesn't break . . .
    	arrRestaurant_count = -1
    end if
    %>
    
    <table cellpadding="5" cellspacing="0" border="0">
    <tr>
    	<td align="right"><strong>Select a Restaurant</strong></td>
    	<td><%'open the initial select box %>	
    		<select name="restaurantSelect" onChange="go(this)">
    		<option value="-1">Choose a Restaurant</option>
    		<%
    		'loop through all records in the array and write
    		' out options for the select box
    		for i = 0 to arrRestaurant_count
    			Response.Write "<option value=""" & arrRestaurant(0,i) _
    				& """>" & arrRestaurant(1,i) & "</option>" & vbCRLf & vbTab
    		next %>
    		</select>
    	</td>
    </tr>
    <tr>
    	<td align="right"><strong>Restaurant Name</strong></td>
    	<td><input type="text" name="restaurantText" size="25"></td>
    </tr>
    </table>
    
    <script language="JavaScript">
    <!--
    	function go(thisValue)
    	{
    		var restaurantText = document.javaRestaurant.restaurantText
    		
    		//If the person is choosing the first options in the select box
    		//	set the value of the restaurant name text box to nothing . . .
    		if (thisValue.value == "-1")
    		{
    			restaurantText.value = ""
    		}
    		else
    		{
    			//Set the restaurant name text box to the same thing that's in the
    			//restaurant name select box.
    			restaurantText.value = thisValue.options[thisValue.selectedIndex].text
    		}
    	}
    //-->
    </script>
    
    
    So . . . the next step is to use ASP inside of your JavaScript to determine if the selected restaurant delivers or not to see an example look at article_2_source.htm in the download provided below

    I pull another column from the database called bDelivery, which is a binary column that will hold either a 0 or a 1. Then add the radio buttons to the HTML elements, and add the following code inside the JavaScript else statement:

    
    <script language="JavaScript">
    <!--
    	function go(thisValue)
    	{
    		...
    		var delivery = document.javaRestaurant.delivery
    
    		if (...)
    			...
    			......
    
    		else
    		{
    			restaurantText.value = thisVal.....
    
    			<% 'loop through the restaurant array using ASP VBScript
    			   for i = 0 to arrRestaurant_count
    
    				'JavaScript statement to see which restaurant has been chosen and
    				'select the proper delivery option . . .
    				'ASP output inside the JavaScript quotes . . . %>
    				if (thisValue.value == "<%= arrRestaurant(0,i) %>")
    				{
    						//Select the index (0 or 1) of the radio button group
    					delivery[<%= arrRestaurant(2,i) %>].checked = true
    				}
    			<% next %>
    		}
    	}
    //-->
    </script>
    
    
    The final (and definitely coolest) step is to have a multiple select box that shows what zip codes each of the restaurants that deliver will go to. (See Example article_3_source.htm in the download)

    I pull all of the distinct zip codes that these restaurants deliver to and put them into the arrZipCodes array. Then I pull all of the zip codes that each restaurant delivers to and put them into the arrRestaurantZipCodes array. This code looks just like this:

    
    'pull all distinct zip codes from database
    dim arrZipCode
    SQL = "select distinct chzipcode " _
    	& "from restaurantzipcodes " _
    	& "where irestaurantid in (select irestaurantid from restaurant  " _
    						& "where vchcity like 's%')"
    	%><!--#include file="../_include/runsql.asp"--><%
    if not rs.eof then
    	arrZipCode = rs.getrows(,,array(0))
    	arrZipCode_count = UBound(arrZipCode,2)
    else
    	arrZipCode_count = -1
    end if
    
    'pull zip codes that each restaurant delivers to
    dim arrRestaurantZipCode
    SQL = "select distinct rzc.irestaurantid, rzc.chzipcode " _
    	& "from restaurantzipcodes rzc, restaurant r " _
    	& "where rzc.irestaurantid  = r.irestaurantid " _
    		& "and (vchcity like 's%') " _
    		& "and r.bdelivery = 1 " _
    	& "order by rzc.irestaurantid"
    	%><!--#include file="../_include/runsql.asp"--><%
    if not rs.eof then
    	arrRestaurantZipCode = rs.getrows(,,array(0,1))
    	arrRestaurantZipCode_count = UBound(arrRestaurantZipCode,2)
    else
    	arrRestaurantZipCode_count = -1
    end if
    
    
    Then I add the multiple select box filled with zip codes to the HTML table and add the following code into the go() JavaScript function.
    
    <script language="JavaScript">
    <!--		
    	
    .........
    ....
    if (...)
    	..
    	...
    	
    else
    	...
    	
    	<% for i = 0 to arrRestaurant_count %>
    		//existing --
    		if (thisValue.value == "<%= arrRestaurant(0,i) %>")
    		//	    |
    		{
    		//	    |
    			delivery[<%= arrRestaurant(2,i) %>].checked = true
    			//  |
    			//-----------
    			deselectAll()					
    										
    			<%
    			'if the selected restaurant does not deliver,
    			'then highlight the 'No Delivery' option
    			'	in the multiple select box
    			if arrRestaurant(2,i) = "0" then %>		
    				x = findIndex("-1")			
    				zipCodes.options[x].selected = true	
    			<%	end if						
    
    			'loop through the array that holds the zip codes
    			'that each of the restaurants deliver to
    			for j = 0 to arrRestaurantZipCode_count
    				'if the restaurant from this inner loop equals
    				'the restaurant from the outer loop
    				if arrRestaurantZipCode(0,j) = arrRestaurant(0,i) then %>
    					x = findIndex("<%= arrRestaurantZipCode(1,j) %>")
    					zipCodes.options[x].selected = true
    			<%		end if	
    			next %>
    		}
    	<% next %>	
    
    						
    	//This is a function to loop through the multiple
    	//select box and return the index of the value passed in . . . 
    	function findIndex(inputStr)
    	{
    		var zipCodes = document.javaRestaurant.zipCodes
    							
    		//Loop through the multiple select box
    		for (i = 0; i < zipCodes.length;i++)
    		{
    			//If the value of the current index equals
    			// what was passed into the function . . . 
    			if (zipCodes.options[i].value == inputStr)
    			{
    				//return the current index
    				return i
    			}
    		}
    		//If we get this far, we didn't find an index,
    		//so we'll pass back a zero.
    		return 0
    	}
    						
    	//This is a function to deselect everything in
    	//the multiple select box.
    	function deselectAll()
    	{
    		var zipCodes = document.javaRestaurant.zipCodes
    							
    		//Loop through the multiple select box
    		for (i=0;i<zipCodes.length;i++)
    		{
    			//Deselect the current index
    			zipCodes.options[i].selected = false
    		}
    	}
    }
    //-->
    </script>
    
    
    This is a large overview of some of the things you can do with ASP, databases, and JavaScript. The possibilities really are quite extensive. Anything that can be done with JavaScript can be dynamically created with ASP.

    This ASP/JavaScript method has not only helped in Carryout, but I seem to find a use for it in just about every site that I make. Good Luck!

    Download

    You can download the complete source for the sample contained in this article:

    http://15seconds.com/files/000210.zip

    About the Author

    Travis Giggy is the vice president of technology for Carryout.Com, an on-line food-ordering service. He also has his own Internet consulting firm called WebAcceleration. Travis lives in Fort Collins, Colorado, and can be reached at travisg@carryout.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Sep 29, 2005 - Migrating to a Load Balanced IIS 6 Environment
    Migration to IIS 6 can present itself as a daunting challenge. Depending on your existing hosting configuration, the process can number in hours, days, or even weeks. Careful planning and research is integral to achieve a successful migration.
    [Read This Article]  [Top]
    Apr 18, 2003 - IIS 6.0: Lessons in Trustworthy Computing
    Microsoft's Trustworthy Computing initiative significantly changed the way in which Microsoft builds and designs software. In this article, Jeff Gonzalez explores some of the new options and architecture in Internet Information Services 6.0.
    [Read This Article]  [Top]
    Mar 25, 2002 - Moving IIS To A Different Server - Part 2
    Brien Posey evaluates two additional methods for migrating a Web server and it settings, backup/restore and ghosting.
    [Read This Article]  [Top]
    Feb 27, 2002 - Moving Your IIS Server to a New Server - Part 1
    Upgrading your server? Brien Posey takes a look at the process and pitfalls of migrating IIS to a completely different server.
    [Read This Article]  [Top]
    Jan 23, 2002 - Troubleshooting IIS Access Problems
    Spending countless hours developing a Web site only to discover that no one can access it is frustrating. This article guides you through the process of troubleshooting Web-site access problems.
    [Read This Article]  [Top]
    Jan 18, 2002 - Running IIS on Windows XP Home Edition?
    Members of the 15Seconds discussion list may have found a way to run IIS on Windows XP Home Edition, so developers can run ASP pages. Attempt at your own risk!
    [Read This Article]  [Top]
    Dec 27, 2001 - Working With IIS Packet Filtering
    Brien Posey discusses IP packet filtering and other ways in which to control access through IIS.
    [Read This Article]  [Top]
    Oct 30, 2001 - Protecting Your IIS Server and Web Application
    Internet viruses such as Code Red and Nimbda have brought down numerous IIS Web servers recently. Fortify and defend your system with this comprehensive strategy authored by 30-year industry veteran, Andrew Novick.
    [Read This Article]  [Top]
    Oct 16, 2001 - Implementing an E-mail Content Filter Using CDO
    Stop SPAM from sliding through your e-mail system. George Walker shows how to create an e-mail content filter for the Windows 2000 SMTP service using Microsoft Collaboration Data Objects.
    [Read This Article]  [Top]
    Mar 25, 1998 - Collaboration Data Object and IIS 4.0
    Collaboration Data Object (CDO) is a COM library designed to send mail through SMTP or Microsoft Exchange. If you install the SMTP server that comes with Microsoft Option Pack 4, you can send mail from an Active Server page using CDO. Because CDO is comes with Microsoft Option Pack 4, CDO is free.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES