| Java Script Beispiele Formbeschreibung für checking Inhalt:
By Robert W. Husted
As a Netscape technology evangelist, I occasionally receive email from developers
asking for assistance with JavaScript. Whenever these requests address an issue that
may be faced by more than one developer, we like to share this information. Recently
I received a message from a developer who was having difficulty reliably preventing a
form submission; he described the problem as follows:
The form the user uses to enter data should NEVER be submitted [to the server].
To achieve this, I use an onSubmit event
handler -- <FORM method=get name="form2" action="none"
onSubmit="checkForm()">.
Every "once in a while," [the checkForm() function] aborts for no obvious
reason,
which results in the form being submitted.
This same problem sometimes occurs when you try to validate form input on the client
side prior to form submission. The onSubmit event handler expects a value back from
the function that is called; if the return value is not a Boolean false, the form is
submitted.
In addition, if JavaScript is disabled on a user's browser, the onSubmit event handler
will
not be triggered and the form will be submitted.
The solution is relatively simple. Avoid using a button of type SUBMIT:
<INPUT TYPE=SUBMIT NAME=SUBMIT VALUE="Submit">
Instead, use a button of type BUTTON:
<INPUT TYPE=BUTTON NAME=SUBMIT VALUE="Submit"
onClick="mySubmitRoutine()">
By eliminating the TYPE=SUBMIT button, you ensure that the user can't submit the form
without your JavaScript function being executed. You should code your JavaScript
routine
to call the form's submit method (after all data checking has successfully been
completed).
function mySubmitRoutine() {
var errors = false;
// CHECK ALL VALUES
// IF NO ERRORS, SUBMIT FORM DATA
if (errors == false) {
// SUBMIT FORM
document.myForm.submit();
}
}
This is the best way to ensure that your JavaScript routines are always executed.
Eliminating the Submit button and submitting your form through JavaScript ensures
that the user does have JavaScript enabled and that the JavaScript code will
execute prior to form submission. (One exception: If your form consists of a single
field, it will be submitted automatically if the user presses the Return key.
To trap for keystrokes by Communicator users in form fields, use the KeyDown,
KeyPress, and KeyUp events in JavaScript 1.2.)
Try to avoid Submit buttons for everything but the most basic forms on your intranet
and extranet. However, do use Submit buttons for Internet forms, which should
support all browsers.
Beispiel Abfrage vor senden!
function start()
{
var errors = false;
// CHECK ALL VALUES
// IF NO ERRORS, SUBMIT FORM DATA
if (errors == false) {
// SUBMIT FORM
document.salut.submit();
alert("Ihr Eintrag wurde übertragen. Herzlichen Dank.");
}
}
// -->< /script></font></h4>
< form name="salut"
method="POST" action="mfo_asp/guestbook.asp">
< p>Name/Vorname</p>
< p><input type="text" size="41" name="Name_Vorname"><br>
Firma< br>
< input type="text"
size="41" name="Firma"></p>
< p>Kommentar:<br>
< textarea rows="2"
name="Kommentar" cols="39"></textarea></p>
< pre><input type="reset" name="B1" value="Zurücksetzen"> <input type="button"
value=" Abschicken" onclick="start()"> </pre>
< /form>
Java Script Guide:
http://home.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
Password Abfrage für eine normale HTML Seite:
function valid(path) {
var password = prompt("Enter the password:", "");
if (password) location.href = path + password + ".html";
}
// -->
</SCRIPT>
Click <A HREF=" javascript:valid('/js/pharmacy/')">here</A>
to enter the password for Doc JavaScript's front page.
Dialog Eingabe "User"
prompt("Enter the password:", "");
//gibt Inhalt zurück ohne ? oder !
Dialog Fenster OK/Cancel
confirm('Yes or No - In You Go')
//Fragezeichen ?
Oeffnen eines Dialogfensters:
//Ausrufezeichen !
< form method="POST">
< p><input
type="submit" name="B1" value="Abschicken"
onclick=" alert('halllo')"></p>
< /form>
Ausgabe von Text:
document.write("Hello, net!")
Oeffnen einer neuen Seite
<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open
Sesame!"
onClick="window.open('mydoc.html', 'newWin')">
//anstelle von newWin kann auch der Target Name angegeben
//werden
</FORM>
Schliessen einer Seite (sich selber)
<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open
Sesame!"
onClick="window.close()">
</FORM>
Letzter Update der Seite:
<SCRIPT language="JavaScript">
<!---
document.write('<h5> Last modify: ')
document.write(document.lastModified)
document.write('</h6>')
// -->
</SCRIPT>
Mail Feedback Form schicken:
Code (A Feedback Form)
<SCRIPT LANGUAGE="JavaScript">
<!--
// Copyright (c) 1997 Mecklermedia Corporation.
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.
function valid(form) {
var field = form.email;
var str = field.value;
if (window.RegExp) {
var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
var reg2str =
"^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
var reg1 = new RegExp(reg1str);
var reg2 = new RegExp(reg2str);
if (!reg1.test(str) && reg2.test(str))
return true;
field.focus();
field.select();
return false;
} else {
if(str.indexOf("@") >= 0)
return true;
field.focus();
field.select();
return false;
}
}
// -->
</SCRIPT>
<FORM METHOD="POST"
ACTION="mailto:you@yourdomain.com?subject=titel"
ENCTYPE="text/plain"
onSubmit="return valid(this)">
Your e-mail address:<BR><INPUT TYPE="text" NAME="email"
SIZE="40"><BR>
Subject:<BR><INPUT TYPE="text" NAME="subject"
SIZE="40"><BR>
Comments:<BR><TEXTAREA NAME="comments" COLS="40"
ROWS="5"></TEXTAREA><BR>
<INPUT TYPE="submit" VALUE="Send Mail">
</FORM>
Files herunterladen
(werden direkt heruntergeladen, falls Filesstruktur gewünscht wird, einfach keinen
Filenamen bei URL eingeben!)
<form action=Fehler! Textmarke nicht definiert. method="POST">
<p><input type="submit" name="B1" value="Java Files
herunterladen..."></p>
</form>
Datumsfunktion
//*********************************************************************************
// function heutigesdatum()
// Beschreibung: Fragt Systemdatum des Clients ab und ändert dieses
// in folgendes Datumsformat dd/mm/yy
// Input: --
// Output: --
// Aktivität: Aendert Formularfeld DateRequest
//*********************************************************************************
function heutigesdatum()
{
var now = new Date();
var yr = now.getYear(); //gibt korrektes Datum aus
var mName = now.getMonth() + 1; //Jan = 0, Feb = 1 etc. - datum plus 1
var ausgabedate = now.getDate() + "/" + mName + "/" + yr;
//getDate() gibt Tag zurück
document.CertForm.DateRequest.value = ausgabedate;
}
Auswahl Combobox mit URL als Inhalt:
<form method="post"
action="http://javascriptsource.com/cgi-bin/navigation/categorymenu.pl">
<select name="url" size="1">
<option
value="http://javascriptsource.com/">JavaScripts!</option>
<option value="http://javascriptsource.com/">###########</option>
<option value="http://bgeffects.javascriptsource.com/">BG
Effects</option>
<option
value="http://buttons.javascriptsource.com/">Buttons</option>
<option
value="http://calculators.javascriptsource.com/">Calculators</option>
<option
value="http://calendars.javascriptsource.com/">Calendars</option>
<option
value="http://clocks.javascriptsource.com/">Clocks</option>
<option
value="http://cookies.javascriptsource.com/">Cookies</option>
<option
value="http://equivalents.javascriptsource.com/">Equivalents</option>
<option
value="http://foldertree.javascriptsource.com/">Foldertree</option>
<option value="http://forms.javascriptsource.com/">Forms</option>
<option value="http://games.javascriptsource.com/">Games</option>
<option
value="http://messages.javascriptsource.com/">Messages</option>
<option
value="http://miscellaneous.javascriptsource.com/">Miscellaneous</option>
<option
value="http://navigation.javascriptsource.com/">Navigation</option>
<option
value="http://page-details.javascriptsource.com/">Page-Details</option>
<option
value="http://passwords.javascriptsource.com/">Pass-Protec.</option>
<option
value="http://scrolls.javascriptsource.com/">Scrolls</option>
<option
value="http://user-details.javascriptsource.com/">User-Details</option>
</select>
</td><td>
<BR>
<INPUT type="image" WIDTH=20 HEIGHT=13
src="http://images.javascriptsource.com/navigation/go.gif"></FORM>
Oeffnen von 3 Frames auf einmal
<FRAMESET cols="85%,15%">
<FRAME SRC="zippy1.html" NAME="A"> This is frames[0]
<FRAMESET rows="33%,33%,33%">
<FRAME SRC="zippy2.html" NAME="B"> This is frames[1]
<FRAME SRC="zippy3.html" NAME="C"> This is frames[2]
<FRAME SRC="zippy4.html" NAME="D"> This is frames[3]
</FRAMESET>
</FRAMESET>
<FORM>
<INPUT TYPE="button" Value="Change Three Frames at Once"
onClick="parent.frames[1].location='zippy5.html';
parent.frames[2].location='zippy6.html';
parent.frames[3].location='zippy7.html';">
</FORM>
Selber kreiert: Bei Drei Frames, damit ich bei einem Klick zwei neue Seiten öffnen
kann in zwei verschieden Frames:
< script language="JavaScript"><!--
function position()
{
window.open("mfo_tips_browser.html", "mfo_haupt");
window.open("mfo_i_position_browser.html", "i_position");
}
// -->< /script>
< p><a href="javascript:position()"><img src="gfx/mfo_Browser.gif"
alt=" Browser? Version,
Eigenschaften etc."
border="0" width="130" height="27"></a>
An zwei ASP/CGI submitten:
function submitToCGI1()
{
document.myForm.action =
"http://graphite/cgi-bin/junhe/echotext/"
document.myForm.submit();
}
Page oeffnen aus einem Pop Up Menu:
<SCRIPT LANGUAGE="JavaScript">
<!--
// Copyright (c) 1997 Mecklermedia Corporation.
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.
function load(form, win) {
// menu - a reference to the select object
// win - a reference to the window object
win.location.href = form.menu.options[form.menu.selectedIndex].value
}
// -->
</SCRIPT>
<-- Example 1 -->
<FORM>
<SELECT NAME="menu" onChange="load(this.form, window)">
<OPTION VALUE="http://www.webreference.com/3d/">3D Animation Workshop
<OPTION VALUE="http://www.webreference.com/js/">Doc JavaScript
<OPTION VALUE="http://www.webreference.com/dlab/">Dmitry's Design Lab
<OPTION VALUE="http://www.webreference.com/dhtml/">Dynamic HTML Lab
<OPTION VALUE="http://www.webreference.com/outlook/">Internet Outlook
</SELECT>
<INPUT TYPE="button" VALUE="Load" onClick="load(this.form,
window)">
<!-- or change "window" to "parent.frames[i]" for a frame target
-->
</FORM>
<-- Example 2 -->
<FORM>
<SELECT NAME="menu" onChange="load(this.form, window)"
SIZE="3">
<OPTION VALUE="http://www.webreference.com/3d/">3D Animation Workshop
<OPTION VALUE="http://www.webreference.com/js/">Doc JavaScript
<OPTION VALUE="http://www.webreference.com/dlab/">Dmitry's Design Lab
<OPTION VALUE="http://www.webreference.com/dhtml/">Dynamic HTML Lab
<OPTION VALUE="http://www.webreference.com/outlook/">Internet Outlook
</SELECT>
<INPUT TYPE="button" VALUE="Load" onClick="load(this.form,
window)">
<!-- or change "window" to "parent.frames[i]" for a frame target
-->
</FORM>
Beim Oeffnen einer Seite eine Funktion aufrufen
<BODY onLoad="chng()" bgColor="FFFFFF">
Beim Schliessen einer Seite eine Funktion aufrufen/ neues Window öffnen
<BODY onUnload="goodBye()">
//Guestbook Seite öffnen, falls ok eingetippt wird
.....
if (confirm("Would you like to sign my Guest Book before leaving?"))
{
alert("\nGREAT!!!\n\nA new window will open and load my Guest Book,\njust close it
when you are done.\n\nHappy Trails!");
window.open("jsguest.htm","newWindow","toolbar=no,location=no,
directories=no,status=yes,menubar=no,resizable=yes,copyhistory=no,
scrollbars=no,width=300,height=300");
}
else
return false;
}
......
Datum abfragen
// get the date and change it to GMT string
var now = new Date();
var yr = now.getYear(); //gibt korrektes Datum aus
var mName = now.getMonth() + 1; //Jan = 0, Feb = 1 etc. - darum plus 1
var ausgabedate = now.getDate() + "." + mName + "." + yr;
//getDate() gibt Tag zurück
document.write(ausgabedate);
Insert in DB
Insert into Employees (FirstName, LastName, EmailName) values
('%%FirstName%%','%%LastName%%','%%EmailName%%')
Form bei Ende Texteingabe soll Inhalt überprüft oder geändert werden
< input type="text"
size="41" name="EMail" onchange="javascript:konvert()">
Mail Adresse, welche in Guestbook erfasst wird umwandeln in Link
< script language="JavaScript"><!--
function konvert(form, emailinhalt)
{
form.EMail.value = "<a href='mailto:" + emailinhalt + "'>" +
emailinhalt + "</a>";
javascript:start();
}
// -->< /script>
< script
language=" JavaScript"><!--
function start()
{
document.salut.submit();
document.salut.action = "mfo_asp/guestbook.asp";
for (var i = 0; i < 100000; i++)
{
}
//alert("Ihr Eintrag wurde übertragen. Herzlichen Dank.");
//location.href="http://mfc_OC1/mfotest/mfo_tips_wünsche.html",
"mfo_haupt";
}
// -->< /script>
< h4>Gästebuch Formular</font> </h4>
< form name="salut"
method="POST">
< input type="hidden"
name="Datum" value="333"><input type="hidden" name="EMail" value><p>Name/Vorname:
< br>
< input type="text"
size="41" name="Name_Vorname"><br>
Firma:< br>
< input type="text"
size="41" name="Firma"> <br>
PLZ/Ort:< br>
< input type="text"
size="41" name="Ort"> <br>
E-Mail:< br>
< input type="text"
size="41" name="EMailKonvert"> <br>
URL ihrer Homepage (optional):< br>
< input type="text"
size="41" name="Url"></p>
< p>Kommentar:<br>
< textarea rows="2"
name="Kommentar" cols="39"></textarea></p>
< pre><input type="reset" name="B1" value="Zurücksetzen"> <input type="button"
value=" Abschicken" onclick="javascript:konvert(salut, EMailKonvert.value)">
</pre>
< /form>
Function um ein Window zu öffnen
function launch(newURL, newName, newFeatures, orgName) {
var remote = open(newURL, newName, newFeatures);
if (remote.opener == null) // if something went wrong
remote.opener = window;
remote.opener.name = orgName;
return remote;
}
//newName _self ist eigenes
Oeffnen einer *.asp Seite, Mail oder DB Eintrag mit vorhergehender Abfrage, ob Inhalt
korrekt (wichtig für IE, da sonst *.asp nicht funktioniert)
< script language="JavaScript"><!--
function konvert(form, suchinhalt)
{
if (!form.C1.checked)
{
form.suchwort.value = "%" + form.suchbegriff.value + "%" ;
form.wildcards.value = "Ja";
}
else
{
form.suchwort.value = form.suchbegriff.value;
form.wildcards.value = "Nein";
}
form.feldbezeichnung.value =
form.feldauswahl.options[form.feldauswahl.selectedIndex].value;
if (suchinhalt)
{
return true;
}
else
{
alert("Bitte erfassen Sie einen Suchbegriff!");
return false;
}
}
//-->< /script>
< form name="rueckweisungscode" action="../asp/rückweisungscode_display.asp" method="POST"
onsubmit="return
konvert(rueckweisungscode, suchbegriff.value);">
//wartet return Wert der obenstehenden Funktion ab, und erst
//wenn true kommt, wird action ausgeführt!!!!!! Gilt auch für Mail
< input type="hidden"
name="feldbezeichnung" value>
....
< input type="submit"
value="Suchen" name="B1>
< input type="reset"
value="Zurücksetzen" name="B2">
</form>
Browser abfragen
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
/*#########################################################
COPYRIGHT NOTICE
-----------------------------------------------------
All text, graphics and logos are Copyright 1997, by
Jeff Rouyer, Sams.net, and IEX. All rights reserved.
You may freely use the JavaScript code and concepts
contained on this page.
###########################################################*/
/*#########################################################
STANDARD BROWSER SNIFFER
-----------------------------------------------------
The Browser Sniffer is used to detect visiting browsers
and assign browser specific attribtues to variables
that will be used in functions.
###########################################################*/
var nav = "";
if(navigator.appName == "Netscape") {
if(parseInt(navigator.appVersion) >= 4) {
nav = "ver4";
} else if(parseInt(navigator.appVersion) == 3) {
nav = "ver3";
} else if(parseInt(navigator.appVersion) == 2) {
nav = "ver2";
}
} else if (navigator.appName == "Microsoft Internet Explorer" &&
navigator.appVersion.indexOf("Macintosh") == -1) {
if(parseInt(navigator.appVersion) >= 4) {
nav = "ver4";
} else if(parseInt(navigator.appVersion) == 3) {
nav = "ver3";
}
} else {
nav = "verx";
}
if (nav == "ver4") {
var screen_height = screen.height;
var screen_width = screen.width;
if (screen_height >= 768) {
background_file = "images/horizon768.jpg";
} else if (screen_height >= 624) {
background_file = "images/horizon624.jpg";
} else if (screen_height >= 600) {
background_file = "images/horizon600.jpg";
} else if (screen_height >= 480) {
background_file = "images/horizon480.jpg";
} else {
background_file = "images/horizon600.jpg";
}
}
function openGuru() {
if(nav == "ver4") {
var screen_width = screen.width-10;
var screen_height = screen.height-30;
var loading = '<HTML><BODY BACKGROUND=' + background_file + '
BGCOLOR="#800000" LINK="#00FFFF" ALINK="#FFFF00"
VLINK="#00FFFF" MARGINWIDTH="0"
MARGINHEIGHT="0"><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><CENTER><FONT
SIZE=5 COLOR="#ECD8AC">Loading
Guru...</FONT></CENTER></BODY></HTML>';
var frames = '<HTML><HEAD><TITLE>Sams.net Dynamic HTML Guru
Resource</TITLE></HEAD><FRAMESET ROWS="0,*"
FRAMEBORDER="0" FRAMESPACING="0" BORDER="0">';
frames += '<FRAME SRC="about:blank" BORDER="0"
MARGINHEIGHT="0" MARGINWIDTH="0" NAME="SNEAK"
SCROLLING="NO">'
frames += '<FRAME SRC="about:blank" BORDER="0"
MARGINHEIGHT="0" MARGINWIDTH="0" NAME="GURU"
SCROLLING="NO">'
frames += '</FRAMESET></HTML>';
var guruWindow = window.open('','guruCanvas','width=' + screen_width + ',height=' +
screen_height + ',top=0,left=0');
guruWindow.document.write(frames);
guruWindow.document.close();
guruWindow.SNEAK.document.open();
guruWindow.SNEAK.document.write(loading);
guruWindow.SNEAK.document.close();
guruWindow.GURU.document.open();
guruWindow.GURU.document.write(loading);
guruWindow.GURU.document.close();
guruWindow.GURU.location.href = "interface/guru.htm";
}
}
// End -->
</SCRIPT>
How do I find a particular character like a "/" for files?
<script language=javascript>
var caller = "http://www.wildmantim.com/asg/index.html";
//this routine looks for "/" to keep only the directory structure from
//the caller's URL
function StripFileName(caller){
for (var i = 0; i <= caller.length; i++) { //charAt finds the location of the
character of interest c="caller.charAt(caller.length" i);
if(c="="/"){" return caller.substring(0,caller.length i ); break;} }
return caller; } </script>
How do I strip unwanted characters from a string ?
<script language=javascript>
var key = " tim,sandy,john,angela "; /./possible real string for a comma
delimited search
var stripped_string = stripInput(key); //call function to remove unwanted characters
function stripInput(key) {
//strip any leading commas,spaces or quotes
while(key.substring(0,1) == "," || key.substring(0,1) == " " ||
key.substring(0,1) == '"' ) {
key = key.substring(1,key.length);}
//strip any trailing commas or spaces
while(key.substring(key.length-1,key.length) == ","
|| key.substring(key.length-1,key.length) == " "
|| key.substring(key.length-1,key.length) == '"') {
key = key.substring(0,key.length-1);}
return key;
}
</script>
How can I redirect a visitor to separate pages, keeping the domain name they came in
with based on the referrer?
Using JavaScript I can think of two possible solutions, one that will not work on MSIE
and the other that will work on all JavaScript capable browsers:
<SCRIPT LANGUAGE="JavaScript"><!--
var who = document.referrer;
if (who.indexOf('www.domain1.com') != -1)
window.location.href = 'http://www.domain1.com/domain1/';
if (who.indexOf('www.domain2.com') != -1)
window.location.href = 'http://www.domain2.com/domain2/';
else
alert('Where DID you come from?');
//--></SCRIPT>
This replaces the normal link to Yahoo with a link to a JavaScript function which you
can then use to change the documents location:
<SCRIPT LANGUAGE="JavaScript"><!--
function functionName(url) {
// test to see if the url has a http: in it:
if (url.indexOf('http:') >-1 ) {
// absolute url, potential external link
// test to see if its within my site
if (url.indexOf('www.mysite.com') > -1) {
// phew !
}
else {
// external so say goodbye
// put your own code here
}
else {
// relative url, therefore within site
}
// now go to url
location.href = url;
}
//--></SCRIPT>
Zeigt die Seite, von wo der User kommt
<SCRIPT LANGUAGE="JavaScript">
<!-- This script and many more are available online from -->
<!-- The JavaScript Source!! http://javascriptsource.com -->
<!-- Begin
document.write("<B>Thanks for visiting us from
"+document.referrer+"</B><P>");
// End -->
</SCRIPT>
Text/Bilder fest positionieren auf einer Seite
<IMG STYLE="position:absolute; TOP:35px; LEFT:170px; WIDTH:50px;
HEIGHT:50px" SRC="circle.gif">
<DIV style="position: absolute; top:80px; left:400px; width:200px;
height:25px">80 from the top and 400 from
the left</DIV>
|