Register

If this is your first visit, please click the Sign Up now button to begin the process of creating your account so you can begin posting on our forums! The Sign Up process will only take up about a minute of two of your time.

Results 1 to 7 of 7
  1. #1
    Junior Member
    Join Date
    Jul 2007
    Posts
    18
    Member #
    15547
    Ok so I think this is a pretty straight forward question with an easy answer. I'm a web designer, definitely not a programmer/coder so I need a little help with this javascript here and was hoping someone could give me a simple answer.

    If you look at the coding for my form below you will see there is the form and then there is a huge chunk of javascript coding that basically checks all the required fields and validates the email address field to make sure everything is filled out before the form can be submitted. The problem is this... I don't want to have that huge long javascript just sitting in an HTML page with the form. I'd rather put it in an external .js file and call it something like "form.js" and then call on the file in the <head> of the HTML document with something like this...

    <script type="text/javascript" src="form.js"></script>

    So if I do something like that and put the java code in an external .js file you will then see towards the beginning of the form where it calls on one of the javascript functions...

    onSubmit="javascript: return CheckRequiredFields();"

    Now I obviously can't use that call right there because that would be assuming the javascript code was still sitting inside of my HTML page which is is not, it's going to be in an external .js file called "form.js". So how do I go about changing that "onSubmit" code when the javascript code is now in it's own external file?

    I hope what I just explained made sense and I hope someone can give me an easy answer =] THANKS!

  2.  

  3. #2
    Junior Member
    Join Date
    Jul 2007
    Posts
    18
    Member #
    15547
    Here is the code from my HTML page. You will see the Javascript at the bottom that I want to put in the external "form.js" file...

    Code:
    <form action="http://adz2go.com/mailmgt/SaveEnteredData.asp" target="_blank" method="post" name="FormName" onSubmit="javascript: return CheckRequiredFields();">
    
                      <input type="hidden" name="BannerAdUniqueId" value="ZBAQAZWRVU">
    <table border=0 cellpadding=0 cellspacing=4>
    <tr>
    <td class="free_newsletter"><p>Subscribe to our<br />
          <span class="free">FREE</span> Newsletter! </p>  </td>
    	</tr>
    <tr>
      <td><input name="*F6247" type="text" class="forms" onfocus="if(this.value=='First Name'){this.value=''}" onblur="if(this.value==''){this.value='First Name'}" value="First Name" size="16" maxlength="500" align="left" /></td>
    </tr>
    <tr>
    <td><input name="*F6248" type="text" class="forms" onfocus="if(this.value=='Last Name'){this.value=''}" onblur="if(this.value==''){this.value='Last Name'}" value="Last Name" size="16" maxlength="500" align="left" /></td>
    	</tr>
    <tr>
    <td><input name="*F6249" type="text" class="forms" onfocus="if(this.value=='Email'){this.value=''}" onblur="javascript: validateEmailAddress(this);if(this.value==''){this.value='Email'}" value="Email" size="16" maxlength="500" align="left" /></td>
    	</tr>
    <tr>
      <td><select name="*F6268" class="forms">
        <option value="United States" selected="selected">United States</option>
        <option value="Ascension Island">Ascension Island</option>
        <option value="Andorra">Andorra</option>
        <option value="United Arab Emirates">United Arab Emirates</option>
        <option value="Afghanistan">Afghanistan</option>
        <option value="Antigua and Barbuda">Antigua and Barbuda</option>
        <option value="Anguilla">Anguilla</option>
        <option value="Albania">Albania</option>
        <option value="Armenia">Armenia</option>
        <option value="Netherlands Antilles">Netherlands Antilles</option>
        <option value="Angola">Angola</option>
        <option value="Antarctica">Antarctica</option>
        <option value="Argentina">Argentina</option>
        <option value="American Samoa">American Samoa</option>
        <option value="Austria">Austria</option>
        <option value="Australia">Australia</option>
        <option value="Aruba">Aruba</option>
        <option value="Azerbaijan">Azerbaijan</option>
        <option value="Bosnia and Herzegovina">Bosnia and Herzegovina</option>
        <option value="Barbados">Barbados</option>
        <option value="Bangladesh">Bangladesh</option>
        <option value="Belgium">Belgium</option>
        <option value="Burkina Faso">Burkina Faso</option>
        <option value="Bulgaria">Bulgaria</option>
        <option value="Bahrain">Bahrain</option>
        <option value="Burundi">Burundi</option>
        <option value="Benin">Benin</option>
        <option value="Bermuda">Bermuda</option>
        <option value="Madagascar">Madagascar</option>
        <option value="Marshall Islands">Marshall Islands</option>
        <option value="Macedonia">Macedonia</option>
        <option value="Mali">Mali</option>
        <option value="Myanmar">Myanmar</option>
        <option value="Mongolia">Mongolia</option>
        <option value="Macau">Macau</option>
        <option value="Northern Mariana Islands">Mariana Islands</option>
        <option value="Martinique">Martinique</option>
        <option value="Mauritania">Mauritania</option>
        <option value="Montserrat">Montserrat</option>
        <option value="Malta">Malta</option>
        <option value="Mauritius">Mauritius</option>
        <option value="Maldives">Maldives</option>
        <option value="Malawi">Malawi</option>
        <option value="Mexico">Mexico</option>
        <option value="Malaysia">Malaysia</option>
        <option value="Mozambique">Mozambique</option>
        <option value="Namibia">Namibia</option>
        <option value="New Caledonia">New Caledonia</option>
        <option value="Niger">Niger</option>
        <option value="Norfolk Island">Norfolk Island</option>
        <option value="Nigeria">Nigeria</option>
        <option value="Nicaragua">Nicaragua</option>
        <option value="Netherlands">Netherlands</option>
        <option value="Norway">Norway</option>
        <option value="Nepal">Nepal</option>
        <option value="Nauru">Nauru</option>
        <option value="Niue">Niue</option>
        <option value="New Zealand">New Zealand</option>
        <option value="Oman">Oman</option>
        <option value="Panama">Panama</option>
        <option value="Peru">Peru</option>
        <option value="French Polynesia">French Polynesia</option>
        <option value="Papua New Guinea">Papua New Guinea</option>
        <option value="Philippines">Philippines</option>
        <option value="Pakistan">Pakistan</option>
        <option value="Poland">Poland</option>
        <option value="St. Pierre and Miquelon">St. Pierre and Miquelon</option>
        <option value="Pitcairn">Pitcairn</option>
        <option value="Puerto Rico">Puerto Rico</option>
        <option value="Palestine">Palestine</option>
        <option value="Portugal">Portugal</option>
        <option value="Palau">Palau</option>
        <option value="Paraguay">Paraguay</option>
        <option value="Qatar">Qatar</option>
        <option value="Reunion">Reunion</option>
        <option value="Romania">Romania</option>
        <option value="Russian Federation">Russian Federation</option>
        <option value="Rwanda">Rwanda</option>
        <option value="Saudi Arabia">Saudi Arabia</option>
        <option value="Solomon Islands">Solomon Islands</option>
        <option value="Seychelles">Seychelles</option>
        <option value="Sudan">Sudan</option>
        <option value="Sweden">Sweden</option>
      </select></td>
    </tr>
    <tr>	
    	<td align="center">
    	  <input name="Submit" type="submit" class="form_buttons" id="Submit" value="Subscribe">
    	  <input type="hidden" name="EmailFieldId" value="*F6249" /></td>
    	</tr>
    </table>
    <SCRIPT LANGUAGE='Javascript'>
    var jsWidth = '' + '';
    var jsHeight = '' + '';
    if (jsWidth != '' && jsHeight != ''){
    if (navigator.userAgent.indexOf('MSIE') != -1) {
    top.resizeTo(parseInt(jsWidth),parseInt(jsHeight));
    }
    else if (navigator.appName.indexOf('Netscape') != -1) {
    top.outerWidth=parseInt(jsWidth);
    top.outerHeight=parseInt(jsHeight);
    }
    }
    </SCRIPT>
    
    </form>
    
    <script language="javascript">
    <!--
    function changeval(what,str,k)
    	{
    		var strmain = '';
    		var strdd = '';
    		var strmm = '';
    		var stryy= '';
    		if (k==0)
    		{
    			strmain='F'+str;
    			strdd = 'dd'+str;
    			strmm = 'mm'+str;
    			stryy = 'yy'+str;			
    		}
    		else
    		{
    			strmain='*F'+str;
    			strdd = '*dd'+str;
    			strmm = '*mm'+str;
    			stryy = '*yy'+str;
    		}
        selected1 = what.elements[''+strmm].selectedIndex;
        if(selected1==-1)
    	value1='';
    	else
    	value1 = what.elements[''+strmm].options[selected1].value;
    
        selected2 = what.elements[''+strdd].selectedIndex;
    	if(selected2==-1)
    		value2='';
    	else
        value2 = what.elements[''+strdd].options[selected2].value;
    
        selected3 = what.elements[''+stryy].selectedIndex;
    	if(selected3==-1)
    		value3='';
    	else
        value3 = what.elements[''+stryy].options[selected3].value;
    	what.elements[''+strmain].value = value1 + '/' +value2 + '/' +value3+'';
    }
    		var radioarray = new Array();
    	//Make sure all required fields are entered
    	function CheckRequiredFields() {
    		var elementname;
    		var elementvalue;
    		var elementtype;
    		var emailvalue;
    		var emailagainvalue;
    		var nochecked=0;
    
    		//Loop through all elements on the page
    		for (var i=0; i < document.forms[0].elements.length; i++) {
    
    			elementtype = document.forms[0].elements[i].type;
    			
    			//If the first position of the element name equals "*"
    			elementname = document.forms[0].elements[i].name;
    	
    
    			//Save the value of the email field
    			if (elementname == '*email') {
    				emailvalue = document.forms[0].elements[i].value;
    			}
    
    			//Save the value of the email again field
    			if (elementname == '*emailagain') {
    				emailagainvalue = document.forms[0].elements[i].value;
    			}
    			//If this is a required field
    			if (elementname.substr(0,1) == '*') {
    			elementvalue = document.forms[0].elements[i].value;
    					if (elementtype.indexOf('radio') > -1) 
    					{
    						addarray(elementname);
                			if (document.forms[0].elements[i].checked) 
    						{
    						nochecked++;
    						}
            			}
    					
            			if (elementtype.indexOf('select') > -1)
                		if (document.forms[0].elements[i].selectedIndex == 0) 
    					{
    						if((elementname.indexOf('*dd')>-1)||(elementname.indexOf('*mm')>-1)||(elementname.indexOf('*yy')>-1))
    						{
    							if(trim(elementvalue)=="0"||trim(elementvalue)=="00")
    							{	
    									alert('Invalid Date. Please try again');
    									return false;
    							}
    						}
    						if((trim(elementvalue)==" ") || (elementvalue.indexOf('Select') > -1))
    						{
    						alert('All required fields have not been entered.');
    						return false;
    						}
    					}
        
            
    								
    				//If the value is empty
    				if (elementvalue.length == 0 || trim(elementvalue) == " ") {
    					alert('All required fields have not been entered.');
    					return false;
    				}
    			}
    		}
    		
    //    if (radioButtons && !radioChecked)
    	if(radioarray.length!=nochecked)
    	{
    					alert('All required fields have not been entered.');
    					return false;
    	
    	}
    
    
    		if (emailvalue != emailagainvalue) {
    			alert('Your email address must be entered the same way twice.');
    			return false;
    		}
    
    		return true;
    	}
    
    function addarray(elementname){
    var flag=0;
    for (var i=0;i<radioarray.length;i++)
    {
    	if(radioarray[i]==elementname)
    	flag = 1;
    }
    if(flag==0)
    radioarray[radioarray.length] = elementname;
    }
    	/// This checks the string passed in as a domain name and requires that it
    	///   either end in one of the '.com' style endings or ends with '.cc' where the
    	///   'cc' represents two alphabetic characters of a country code domain.
    	///   I don't actually check for a valid country code, only for the proper form.
    	/// This function needs JS1.2 and does not work in Opera3.5
    	function isStandardDomain(domainIn) {
    
    		/// The value to return, start out assuming invalid domain.
    		var isStandardReturn = false;
    
    		/// Holds the last 4 characters of domain name.
    		var last4chars  =  domainIn.substring( domainIn.length-4, domainIn.length );
    
    		/// Holds the last 3 characters of domain name.
    		var last3chars  =  domainIn.substring( domainIn.length-3, domainIn.length );
    
    		/// Uppercase it for comparison purposes.
    		last4chars = last4chars.toUpperCase();
    
    		/// A regular expression pattern to match country code domains.
    		///  In otherwords a Dot character followed by two alphabetic characters.
    		/// NOTE:  This line doesn't work at all in Opera3.5 and prevents the
    		///  entire script from running!!!  BUMMER!!!
    		///  It also seems to not work in Opera4.02 but only prevents
    		///  the 2 letter codes from working but doesn't crash the script.
    		var countryCodePattern = /\.[a-zA-Z][a-zA-Z]/;
    
    		if      ( last4chars == ".COM" ) isStandardReturn = true;
    		else if ( last4chars == ".EDU" ) isStandardReturn = true;
    		else if ( last4chars == ".GOV" ) isStandardReturn = true;
    		else if ( last4chars == ".NET" ) isStandardReturn = true;
    		else if ( last4chars == ".MIL" ) isStandardReturn = true;
    		else if ( last4chars == ".ORG" ) isStandardReturn = true;
    		else if ( last4chars == ".BIZ" ) isStandardReturn = true;
    		else if ( last3chars.search( countryCodePattern )   !=  -1 )
    
    		isStandardReturn = true;
    
    		return  isStandardReturn;
    
    	} // Ends isStandardDomain(domainIn)
    
    
    	/// Checks basic validity of an email address that's passed in.
    	///  Requires proper configuration of the '@' character lack of Spaces
    	///  and calls function "isStandardDomain()" to check on the form of the
    	///  domain name part.
    	/// Used an alert box to display it's answer.
    	/// This function needs JS1.2 [because isStandardDomain() does] and does not work in Opera3.5.
    	function  validateEmailAddress(objName) {
    
    		var emailIn;
    		emailIn = objName.value;
    
    		/// Number of '@' chars present in input string.
    		var numAtChars;
    
    		/// The part of input address before the '@' character.
    		var userNameIn;
    
    		/// The part of input address after the '@' character.
    		var domainNameIn;
    
    		/// Holds the fields of the entered address, delimitted by '@' chars.
    		var addressFields = new Array();
    
    		// Concatenate all alert output to here.
    		var alertString = "";
    
    		/// Divide the input email address into fields.
    		///  Note that the array "addressFields" will have one more element
    		///  than the number of '@' signs in the input string.
    		/// IE4 handles this OK with '@' as last character but NS4,4.5 and Opera 3.5 don't.
    		addressFields = emailIn.split('@');
    
    		numAtChars = addressFields.length - 1;
    
    		alertString += "Email Address ";
    
    		if ( emailIn == "" )
    			alertString += "must be entered.";
    
    		else if ( numAtChars  ==  0 )
    			alertString += "contains no '@' character and is therefore Not a valid Email Address.";
    
    		else if ( numAtChars  >  1 )
    			alertString += "contains " + numAtChars + " '@' characters and is therefore Not a valid Email Address.";
    
    		else if ( addressFields[0] == "" )
    			alertString += "has no Username before the '@' character and is therefore Not a valid Email Address.";
    
    		else if ( addressFields[1] == "" )
    			alertString += "has no Domain Name after the '@' character and is therefore Not a valid Email Address.";
    
    		else {
    			userNameIn   = addressFields[0];
    			domainNameIn = addressFields[1];
    
    			if ( userNameIn.indexOf( " " ) != -1 )
    				alertString += "has one or more Spaces in the Username before the '@' character and is therefore Not a valid Email Address.";
    			else if ( domainNameIn.indexOf( " " ) != -1 )
    				alertString += "has one or more Spaces in the Domain Name after the '@' character and is therefore Not a valid Email Address.";
    			else if ( isStandardDomain( domainNameIn ) == false )
    				alertString += "does not end with a '.com' style domain or two letter country code domain and is therefore Not a valid Email Address.";
    			else
    				alertString = "";
    
    		} // Ends else from outer string of if-then-else's.
    
    		// Post the alert box.
    		if (alertString.length > 0) {
    			alert(alertString);
    			objName.focus();
    			return false;
    		}
    
    		return true;
    
    	} // Ends validateEmailAddress(objName)
    
    	function isEmpty(objName) {
    		var field;
    		var fieldvalue;
    		field = objName;
    		fieldvalue = field.value;
    		if (fieldvalue.length == 0) {
    			alert("This is a required field.");
    			objName.focus();
    		}
    	}
    
    	function checkdate(objName) {
    		var datefield = objName;
    		if (chkdate(objName) == false) {
    			datefield.select();
    			alert("The date is invalid.  Please try again.");
    			datefield.focus();
    			return false;
    		}
    		else {
    			return true;
    		}
    	}
    
    	//Validate a date field
    	function chkdate(objName) {
    		var strDatestyle = "US"; //United States date style
    		//var strDatestyle = "EU";  //European date style
    		var strDate;
    		var strDateArray;
    		var strDay;
    		var strMonth;
    		var strYear;
    		var intday;
    		var intMonth;
    		var intYear;
    		var booFound = false;
    		var datefield = objName;
    		var strSeparatorArray = new Array("-"," ","/",".");
    		var intElementNr;
    		var err = 0;
    		var strMonthArray = new Array(12);
    		strMonthArray[0] = "Jan";
    		strMonthArray[1] = "Feb";
    		strMonthArray[2] = "Mar";
    		strMonthArray[3] = "Apr";
    		strMonthArray[4] = "May";
    		strMonthArray[5] = "Jun";
    		strMonthArray[6] = "Jul";
    		strMonthArray[7] = "Aug";
    		strMonthArray[8] = "Sep";
    		strMonthArray[9] = "Oct";
    		strMonthArray[10] = "Nov";
    		strMonthArray[11] = "Dec";
    		strDate = datefield.value;
    
    		//If the date field is empty, return without validating
    		if (strDate.length < 1) {
    			return true;
    		}
    
    		//Retrieve the month, day and year portions of the date
    		for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
    			if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
    				strDateArray = strDate.split(strSeparatorArray[intElementNr]);
    				if (strDateArray.length != 3) {
    					err = 1;
    					return false;
    				}
    				else {
    					strDay = strDateArray[0];
    					strMonth = strDateArray[1];
    					strYear = strDateArray[2];
    				}
    				booFound = true;
    			}
    		}
    
    		if (booFound == false) {
    			if (strDate.length > 5) {
    				strDay = strDate.substr(0, 2);
    				strMonth = strDate.substr(2, 2);
    				strYear = strDate.substr(4);
    			}
    			else
    				return false;
    		}
    
    		//If year is only 2 positions long, then prefix with "20"
    		if (strYear.length == 2) {
    			strYear = '20' + strYear;
    		}
    
    		// US style
    		if (strDatestyle == "US") {
    			strTemp = strDay;
    			strDay = strMonth;
    			strMonth = strTemp;
    		}
    
    		intday = parseInt(strDay, 10);
    
    		if (isNaN(intday)) {
    			err = 2;
    			return false;
    		}
    
    		intMonth = parseInt(strMonth, 10);
    
    		if (isNaN(intMonth)) {
    			for (i = 0;i<12;i++) {
    				if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
    					intMonth = i+1;
    					strMonth = strMonthArray[i];
    					i = 12;
    				}
    			}
    			if (isNaN(intMonth)) {
    				err = 3;
    				return false;
    			}
    		}
    
    		intYear = parseInt(strYear, 10);
    
    		if (isNaN(intYear)) {
    			err = 4;
    			return false;
    		}
    
    		if (intMonth>12 || intMonth<1) {
    			err = 5;
    			return false;
    		}
    
    		if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
    			err = 6;
    			return false;
    		}
    
    		if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
    			err = 7;
    			return false;
    		}
    
    		if (intMonth == 2) {
    			if (intday < 1) {
    				err = 8;
    				return false;
    			}
    			if (LeapYear(intYear) == true) {
    				if (intday > 29) {
    					err = 9;
    					return false;
    				}
    			}
    			else {
    				if (intday > 28) {
    					err = 10;
    					return false;
    				}
    			}
    		}
    
    		return true;
    	}
    
    	//Determine if year is a leap year
    	function LeapYear(intYear) {
    		if (intYear % 100 == 0) {
    			if (intYear % 400 == 0) { return true; }
    		}
    		else {
    			if ((intYear % 4) == 0) { return true; }
    		}
    		return false;
    	}
    
    	function trim(stringToTest)
    	{
        	var kk
        	var subStart
        	var subEnd
    
    			if (stringToTest == null)
    				 return (" ")
    			if (stringToTest.length == 0)
           	return (" ")
    
    
        	subStart = (-1)
        	for (kk=0;kk<stringToTest.length;kk++)
        	{
            	if (stringToTest.charAt(kk) > " ")
            	{
              	subStart = kk
              	break;
            	}
        	}
    
        	for (kk=stringToTest.length;kk>=0;kk--)
        	{
            	if (stringToTest.charAt(kk) > " ")
            	{
               	subEnd = kk
               	break;
            	}
        	}
    
        	if (subStart < 0)
           	return (" ")
        	return (stringToTest.substr(subStart,subEnd+1))
    	}
    
    // -->
    </script>

  4. #3
    WDF Staff smoseley's Avatar
    Join Date
    Mar 2003
    Location
    Boston, MA
    Posts
    9,729
    Member #
    819
    Liked
    205 times
    No need for the "javascript: " prefix - "onSubmit" is an event that only launches javascript.

    Try this:
    Code:
    onSubmit="return CheckRequiredFields();"

  5. #4
    Junior Member
    Join Date
    Jul 2007
    Posts
    18
    Member #
    15547
    But what if I have several java script calls in the head of my HTML page? How will it know which javascript file that "CheckRequiredFields();" function is in?

    The head of my HTML page looks like this...

    <script type="text/javascript" src="bookmark.js"></script>
    <script type="text/javascript" src="sendpage.js"></script>
    <script type="text/javascript" src="form.js"></script>

  6. #5
    WDF Staff smoseley's Avatar
    Join Date
    Mar 2003
    Location
    Boston, MA
    Posts
    9,729
    Member #
    819
    Liked
    205 times
    You'll have to check each of the files to find the function, and make sure there is no duplication of function names... that could mess things up.

  7. #6
    Senior Member
    Join Date
    Jun 2005
    Location
    Atlanta, GA
    Posts
    4,146
    Member #
    10263
    Liked
    1 times
    Consider the script tags as telling the browser `include these files as if they were a part of this HTML file'. It doesn't exactly mean that, but it does something that equates to about the same from your point of view. So it doesn't need to know *which* of those files the function is in, it just needs to know that it's in one of those files, because they are, as far as it is concerned, part of the page.

  8. #7
    Junior Member
    Join Date
    Aug 2007
    Posts
    6
    Member #
    15662
    <script type="text/javascript" src="SCRIPT NAME.js"></script>

    Bruce


Remove Ads

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
All times are GMT -6. The time now is 02:25 AM.
Powered by vBulletin® Version 4.2.3
Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.
vBulletin Skin By: PurevB.com