Description |
Tip |
Handling multiple Select options with javascript | While the HTML Select form control allows multiple selections, you may
have wondered how to manipulate those selections, for inclusion in a
database, for example. ASP offers several ways to do so. Of course,
client-side script and the DOM give you one way to do so. When you use
this technique, the basic idea consists of looping through the control's
options, check each option's Selected property, and where appropriate,
enter the value and text directly into a database or an array, as seen
below: <head> <script language="javascript"> function getSelected() { var sConnect = "Provider=Microsoft.Jet.OLEDB.3.51;Data " + "Source=D:\\Inetpub\\wwwroot\\ZDJindex\\index.mdb" var adoRst = new ActiveXObject("ADODB.Recordset") adoRst.open("tblDays", sConnect, 2, 2) //2-dynamic keyset, 2-table command var objSelect = document.forms["frm1"].elements["sel1"] var msg = new String("") //Insert selected items for (x=0; x<objSelect.length; x++) { if (objSelect.options[x].selected) { adoRst.AddNew() adoRst.Fields("Day") = objSelect.options[x].text adoRst.Fields("Value") = objSelect.options[x].value adoRst.Update() msg += objSelect.options[x].text + ", " } } adoRst.close() //Strip the trailing comma msg = msg.substring(0, msg.length-2) //Show selected items alert(msg) } </script> <body> <form id="frm1"> <select size=10 multiple="multiple" id="sel1"> <option value="1">Sunday</option> <option value="2">Monday</option> <option value="3">Tuesday</option> <option value="4">Wednesday</option> <option value="5">Thursday</option> <option value="6">Friday</option> <option value="7">Saturday</option> </select> <input type="button" value="Show Selections" onclick="getSelected()" /> </form> </body> While this script works just fine on the client-side in Internet Explorer, don't try the same technique when you post a form to server-side ASP. That's because the multiple selections get passed as a comma-delimited string. In an upcoming tip, we'll show you two different ways parse this string on the server side. |
Quickly determine client browser types in javascript code | The document object model and ASP pages offer several ways to determine
a client's browser type. Most, however involve long parsing routines that
search for specific substrings within a larger string. Fortunately, using
javascript, there's a quick way to determine if the client browser is
either Netscape Navigator 4+ or Internet Explorer 4+. The basic idea is
that you test for objects in the browser's DOM that don't exist in the
other browser's DOM. For example, IE 4.0 + browsers include the
document.all collection, while NN4.0 + browsers support the
document.layers collection. If one of these objects is null, then your
code can infer that the client is the other browser type. For example, the
following script displays the boolean results of each test when you load a
Web page: <script language="javascript"> var nav4 = !(document.layers == null) var iex4 = !(document.all == null) alert("Nav: " + nav4 + " IE4: " + iex4) </script> As you can see, the first expression sets the nav4 variable equal to the opposite of document.layers==null. So, if you view this page in an IE 4+ browser, document.layers is null, and the entire expression evaluates to false. |
Internet Explorer Add to Favorites | To create a button that allows the user to add the page being viewed to
their Internet Explorer Favorites folder put the following in the
<head> section of the page.
Then in the body of the page where you want the link to be place the following:
Only Internet Explorer 4+ will display the link. |
Let DateDiff() determine if two dates are in the same month | To determine if two dates are in the same month, your first instinct may be to simply use the Month() function on each date, then compare the two resulting numbers. However, under these circumstances, the comparison would equate 1/1/2000 with 1/1/1999. Instead, the DateDiff() function provides one quick way to make this determination, like so: DateDiff("m", Date1, Date2) In this expression, the DateDiff() function finds the difference in calendar months between the two dates. If the expression returns a zero, then the two dates are in the same calendar month. To include this feature in an conditional expression, you could use the following in a query: SameMonth: IIF(DateDiff("m", Date1, Date2), "No", "Yes") In this expression, Access evaluates any value <> 0 returned by the DateDiff() function as -1, or True (returning 'No'), and 0 as False (returning 'Yes'). |
Calling a script function without user input | The most common way for a script function to be called is by having an
element trap a event, which in turn calls the function, as in: <DIV id = "myelement" onclick = "myfunction()" > Click here </DIV> But what if you want a function to perform some task as soon as the page loads, without any user input? In that case, you can use the onload event, placing it in the BODY element of your page, as in: <BODY onload = "myfunction()" > The function will be called immediately after the page loads, and no user input is required. |
Dynamically loading different files into frames | You can load any number of different files into a frame at runtime using
the frame's location object. As you would when building any project using
frames, first build a file that defines your frame. For our example, we've
defined a frame called myframe. The code below would then go in a separate
file. In the BODY of our code, we've placed a list of files from which the user can choose. When a user clicks on the file name he wants to load, the name of the file is passed as a parameter to the function. The function appends the ".htm" extension to the name, and assigns the complete name to the location object of the frame myframe, which loads the appropriate file into that frame. <HTML> <HEAD> <TITLE> History topics </TITLE> <SCRIPT> function loadfile(whatfile) { parent.myframe.location = whatfile + ".htm"; } </SCRIPT> </HEAD> <BODY> <DIV onclick = "loadfile('file1')" > Load file 1</DIV> <DIV onclick = "loadfile('file2')" > Load file 2</DIV> <DIV onclick = "loadfile('file3')" > Load file 3</DIV> </BODY> </HTML> |
Manually registering ActiveX controls | If you're having trouble placing an ActiveX control on your page, you
may need to explicitly register it in the Windows Registry. Along with the
unique CLSID for the control, the Registry stores information such as the
version of the control, where it's located, etc. You can manually register an ActiveX control from the DOS command prompt. On the command line, type REGSVR32 <path>\<activexfile.ocx> where <path> is the path to the file containing the ActiveX control and <activexfile.ocx> is the name of the file. If the control successfully registers, you'll receive a pop-up window stating that the registration succeeded. If you're not a DOS fan, you can also register the control from the Start menu's Run option in Windows 95/98/NT. One word of caution: be careful not to modify any of the entries in your Windows Registry. Tinkering with the Registry can have disastrous results! Submitted by: Bill Pitzer Contributing Editor, Microsoft Web Builder |
Separate your scripts from your HTML code | You can easily use one script for a variety of different Web pages by
placing your javascript code in a separate file. Create the file in a text
editor, and name it using a .js extension. Then, in your HTML code, assign
that file to the src attribute of a <SCRIPT> tag. For example, if
you've got your script in a file called "validate.js", place a
<SCRIPT> tag in your Web page document like this: <SCRIPT language="javascript" src="validate.js"></SCRIPT> Of course, you can have more than one <SCRIPT> tag within a Web page document. If you place generic functions within a .js file that you assign as a src to one <SCRIPT> tag, you can have a second <SCRIPT> block in your page that contains function calls to the functions within the .js file. This way, you can have several different Web pages calling the generic functions in the .js file, but passing the functions data that is specific to each page. |
Use javascript's floor() method to do integral division | Although javascript does not have a mathematical operator that results
in the integer part of a division operation (called integral division, or
Div in some languages), you can use the Math object's floor() method to
create that result, as long as the values you are working with are
positive. The Math object's floor() method returns the next integer less
than or equal to the value it is passed. For example: var result = Math.floor(5/3) //result = 1 The result is the equivalent of having the decimal part (or remainder) removed after the division operation has taken place, which is exactly what an integral division operation would do. |
Use onSubmit to confirm that your user is ready to submit his form data | Before a user submits a form to the server, use the onSubmit event
handler to ask him if he's really ready to submit the data that he's
entered. Here's how: Suppose your button for submitting the form looks something like this: <INPUT type = "submit" value = "Send Form"> In the <FORM> tag on the page, add the onSubmit event handler, asking it to call a function that will prompt the user, and ask him if he wants to continue with the submission. The <FORM> tag would look like this: <FORM onSubmit = "return sendForm()"> If the onSubmit handler returns true (that is, if the sendForm() function returns a true) submission continues; if it returns false, submission stops. Next, write the sendForm() function, which uses the window object's confirm method to interact with the user: function sendForm() { return confirm("Do you want to continue the submission?") } The confirm method displays a dialog box with the message that's been placed in the parentheses, and two buttons: OK and Cancel. If the user clicks OK the function returns true and submission continues; if he clicks Cancel the function returns false and submission is halted. |
Use the properties of the select list's options array | Use the properties of the select list's options array to access
information about your list options The options in a select list are accessible using the select list's options[] array. In other words, suppose you had a select list like the following: <SELECT name = "memberlist"> <OPTION value = 0> Select a membership category <OPTION value = 100> Family <OPTION value = 75> Single <OPTION value = 50> Senior <OPTION value = 30> Youth </SELECT> The option at memberlist.options[0] would be the first option in the list, memberlist.options[1] would be the second member, etc. But did you know that you can assign a value to the value property of each option, which can provide additional information about the user's selection? And, you can also access the text of the option using the option's text property. Both properties are accessible via the options array. Here's an example. Suppose the user has selected the Single membership option. (selectedIndex = 2). We could then use the following snippet of code in any script: var fee = parseInt(memberlist.options[memberlist.selectedIndex].value) var phrase = memberlist.options[memberlist.selectedIndex].text fee = fee + (fee * 0.07) alert("We welcome you as a " + phrase + " member." + "\n") alert("Please pay $" + fee + " tax included") The code above would display the following message: We welcome you as a Single member. Please pay $8.25 tax included. |
Use the Window object's open method to open locations in a new window | If you have links on your page that will take users away from your site,
consider having the links open a new window rather than having the new
page open in the current window. That way, your users continue to have
your own site in view, and may be more likely to return to it by just
closing the newly opened window. Using the Window object's open method
allows you to not only open a new browser window, but also allows you to
specify the window's size and look. The open method accepts three parameters: A URL to be loaded into the window, an optional name for the window, and an optional string of window features that will determine what the window will look like. For example, the window features can specify whether the window should have a menu bar, location bar, status bar, or scrollbars. They can also specify the size of the window and whether or not it should be resizable. The list of window features that you want your new window to exhibit are placed inside a quoted string, separated by commas, and with no spaces anywhere within the string. Here's an example. To open a new window when a link is clicked, set up the link like this: <A href = "javascript:openwindow('http://www.zdjournals.com')">Check out ZDJ's Daily Buzz!</A> Then, to open a new, unnamed window with a status bar and scrollbars that is 400 pixels high and 600 pixels wide, and is resizable, the script would be: <SCRIPT> function openwindow(address) { window.open(address,"","status,height=400,width=600,scrollbars,resizable") } </SCRIPT> For a full list of the open method's window features, see the Microsoft site at http://msdn.microsoft.com/workshop/Author/dhtml/reference/methods/open_0.asp |
Using the appVersion property with Internet Explorer | The appVersion property of javascript's Navigator object returns the
version of the current browser, along with information about the browser's
platform. For example, running Internet Explorer 4.0 in Windows 95 would
create the following value for the appVersion property: 4.0 (compatible; MSIE 4.01 Windows 95) You might, at first glance, assume that you can simply extract the first character of the appVersion string to determine the version of Internet Explorer that you're using. However, that first number is the compatible Netscape version; the Internet Explorer version is actually to be found in the string "MSIE 4.01." To extract the Internet Explorer version from the string, try using a combination of the indexOf() and charAt() String methods, as in: function getversion() { //Get the position of the string "MSIE" in the appVersion string position = navigator.appVersion.indexOf("MSIE" ) //If the string is found if (position >-1) { //Move to the position of the version number and test switch (navigator.appVersion.charAt(position+5)) { case "3": alert("Using Internet Explorer 3") break case "4": alert("Using Internet Explorer 4") break case "5": alert("Using Internet Explorer 5") break } } else alert("Not using Internet Explorer") } |