JavaScript DHTML/Form Control/Form Submit

Материал из Web эксперт
Перейти к: навигация, поиск

Adjusting a Server Submission Action

   <source lang="html4strict">
  

<html> <head> <title>Checkbox Submission</title> <script type="text/javascript"> function setAction(form) {

   if (form.checkThis.checked) { 
       form.action = form.checkThis.value; 
   } else { 
       form.action = "file://primaryURL"; 
   } 
   return true; 

} </script> </head> <body> <form method="POST" action=""> <input type="checkbox" name="checkThis" value="file://alternateURL" />Use alternate <input type="submit" name="boxChecker" onclick="return setAction(this.form)"/> </form> </body> </html>


 </source>
   
  


Convert a passed form reference to a string formatted like a JavaScript array of objects

   <source lang="html4strict">
  

// Read the name, id, type, and value of one form control element // as requested by form2ArrayString() function formObj2String(obj) {

 var output = "{";
 if (obj.name) {
   output += "name:"" + obj.name + "",";
 }
 if (obj.id) {
   output += "id:"" + obj.id + "",";
 }
 output += "type:"" + obj.type + "",";
 switch (obj.type) {
   case "radio":
     if (obj.name) {
       obj = document.forms[0].elements[obj.name];
       var radioVal = "value:false,index:-1";
       for (var i = 0; i < obj.length; i++) {
         if (obj[i].checked) {
           radioVal = "value:true,index:" + i;
           i = obj.length;
         } 
       }
       output += radioVal;
     } else {
       output += "value:" + obj.checked;
     }
     break;
   case "checkbox":
     output += "value:" + obj.checked;
     break;
   case "select-one":
     output += "value:" + obj.selectedIndex;
     break;
   case "select-multiple":
     output += "value:" + obj.selectedIndex;
     break;
   case "text":
     output += "value:"" + escape(obj.value) + """;
     break;
   case "textarea":
     output += "value:"" + escape(obj.value) + """;
     break;
   case "password":
     output += "value:"" + escape(obj.value) + """;
     break;
   case "hidden":
     output += "value:"" + escape(obj.value) + """;
     break;
   default:
     output += "";
 }
 output += "}"
 return output;

} // Convert a passed form reference to a string formatted like // a JavaScript array of objects function form2ArrayString(form) {

 var elem, lastName = "";
 var output = "[";
 for (var i = 0; i < form.elements.length; i++) {
   elem = form.elements[i];
   if (elem.name && (elem.name != lastName)) {
     output += formObj2String(form.elements[i]) + ",";
     lastName = elem.name;
   }
 }
 output = output.substring(0, output.length-1) + "]";
 return output;

} // Distribute form control values from another source to the // controls in this page"s form, whose names/ids match those // of the original form controls function string2FormObj(form, str) {

 var elem, objArray = eval(str);
 for (var i = 0; i < objArray.length; i++) {
   elem = (objArray[i].name) ? form.elements[objArray[i].name] : document.getElementById(objArray[i].id);
   switch (objArray[i].type) {
     case "radio":
       if (objArray[i].name && objArray[i].value && objArray[i].index >= 0) {
         elem = elem[objArray[i].index];
       }
       elem.checked = objArray[i].value;
       break;
     case "checkbox":
       elem.checked = objArray[i].value;
       break;
     case "select-one":
       elem.selectedIndex = objArray[i].value;
       break;
     case "select-multiple":
       elem.selectedIndex = objArray[i].value;
       break;
     default:
       elem.value = unescape(objArray[i].value);
   }
 }

}



 </source>
   
  


Demo: Ajax form submit

   <source lang="html4strict">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD>

 <title>Demo: Ajax form submit</title>
 <script type="text/javascript">

/************************************************************************************************************ Ajax form submit Copyright (C) 2007 DTHMLGoodies.ru, Alf Magne Kalleland This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Dhtmlgoodies.ru., hereby disclaims all copyright interest in this script written by Alf Magne Kalleland. Alf Magne Kalleland, 2007 Owner of DHTMLgoodies.ru

                                                                                                                                                                                                                        • /

var DHTMLSuite = new Object(); DHTMLSuite.formUtil = function() {


} DHTMLSuite.getEl = function(elRef){

 if(typeof elRef=="string"){
   if(document.getElementById(elRef))return document.getElementById(elRef);
   if(document.forms[elRef])return document.forms[elRef];
   if(document[elRef])return document[elRef];
   if(window[elRef])return window[elRef];
 }
 return elRef;  // Return original ref.
 

}

DHTMLSuite.formUtil.prototype = {

 // {{{ getFamily
   /**
    *  Return an array of elements with the same name
    *  @param Object el - Reference to form element
    *  @param Object formRef - Reference to form
    *
    * @public
    */    
 getFamily : function(el,formRef)
 {
   var els = formRef.elements;
   var retArray = new Array();
   for(var no=0;no<els.length;no++){
     if(els[no].name == el.name)retArray[retArray.length] = els[no];
   }
   return retArray;    
 }
 // }}}
 
 ,
 // {{{ hasFileInputs()
   /**
    *  Does the form has file inputs?
    *  @param Object formRef - Reference to form
    *
    * @public
    */    
 hasFileInputs : function(formRef)
 {
   var els = formRef.elements;
   for(var no=0;no<els.length;no++){
     if(els[no].tagName.toLowerCase()=="input" && els[no].type.toLowerCase()=="file")return true;  
   }
   return false;
 }
 // }}}
 ,  
 // 
 ,  
 // {{{ getValue()
   /**
    *  Return value of form element
    *  @param Object formEl - Reference to form element
    *
    * @public
    */
 getValue : function(formEl)
 {
   switch(formEl.tagName.toLowerCase()){
     case "input":
     case "textarea": return formEl.value;
     case "select": return formEl.options[formEl.selectedIndex].value;      
   }
   
 }
 // }}}
 ,  
 // {{{ areEqual()
   /**
    *  Check if two form elements have the same value
    *  @param Object input1 - Reference to form element
    *  @param Object input2 - Reference to form element
    *
    * @public
    */  
 areEqual : function(input1,input2)
 {
   input1 = DHTMLSuite.getEl(input1);
   input2 = DHTMLSuite.getEl(input2);  
   if(this.getValue(input1)==this.getValue(input2))return true;
   return false;    
 }  

}

/************************************************************************************************************

  • Form submission class
  • Created: March, 6th, 2007
  • @class Purpose of class: Ajax form submission class
  • Css files used by this script: form.css
  • Demos of this class: demo-form-validator.html
  • Update log:
                                                                                                                                                                                                                        • /

/**

  • @constructor
  • @class Form submission
  • Demo: <a href="../../demos/demo-form-validator.html" target="_blank">demo-form-validator.html</a>
  • @param Associative array of properties, possible keys:
  • formRef - Reference to form
  • method - How to send the form, "GET" or "POST", default is "POST"
  • reponseEl - Where to display response from ajax
  • action - Where to send form data
  • responseFile - Alternative response file. This will be loaded dynamically once the script receives response from the file specified in "action".
  • @version 1.0
  • @version 1.0
  • @author Alf Magne Kalleland(www.dhtmlgoodies.ru)
    • /

DHTMLSuite.variableStorage = new Object(); DHTMLSuite.variableStorage.arrayDSObjects = new Array(); DHTMLSuite.form = function(propArray) {

 var formRef;
 var method;
 var responseEl;
 var action;
 var responseFile;
 
 var formUtil;
 var objectIndex;
 var sackObj;
 var coverDiv;
 var layoutCSS;
 var iframeName;
 
 this.method = "POST";
 this.sackObj = new Array();
 this.formUtil = new DHTMLSuite.formUtil();
 this.layoutCSS = "form.css";
 
 
   
 this.objectIndex = DHTMLSuite.variableStorage.arrayDSObjects.length;
 DHTMLSuite.variableStorage.arrayDSObjects[this.objectIndex] = this;  
   
 
 if(propArray)this.__setInitProperties(propArray);
 

} DHTMLSuite.form.prototype = {

 // {{{ submit()
   /**
    *  Submits the form
    *
    * @public
    */    
 submit : function()
 {
   this.__createCoverDiv();
   var index = this.sackObj.length;
   if(this.formUtil.hasFileInputs(this.formRef)){
     this.__createIframe();
     this.formRef.submit();
     
   }else{
     this.__createSackObject(index);      
     this.__populateSack(index);      
     this.sackObj[index].runAJAX();
   }
   this.__positionCoverDiv();
   return false;
 }
 // }}}
 ,
 __createIframe : function()
 {
   if(this.iframeName)return;
   var ind = this.objectIndex;
   var div = document.createElement("DIV");
   document.body.appendChild(div);
   this.iframeName = "DHTMLSuiteForm" + this.getUniqueId();
   div.innerHTML = "<iframe style="visibility:hidden;width:5px;height:5px" id="" + this.iframeName + "" name="" + this.iframeName + "" onload="parent.DHTMLSuite.variableStorage.arrayDSObjects[" + ind + "].__getIframeResponse()"></iframe>"; 
   this.formRef.method = this.method;
   this.formRef.action = this.action;
   this.formRef.target = this.iframeName;  
   if(!this.formRef.enctype)this.formRef.enctype = "multipart/form-data";
     
 }
 ,
 // {{{ getUniqueId()
   /**
    *
    *  Returns a unique numeric id
    *
    *
    * 
    * @public
    */    
 getUniqueId : function()
 {
   var no = Math.random() + "";
   no = no.replace(".","");    
   var no2 = Math.random() + "";
   no2 = no2.replace(".","");    
   return no + no2;    
 }  
 // }}}
 ,
 // {{{ __getIframeResponse()
   /**
    *  Form has been submitted to iframe - move content from iframe
    *
    * @private
    */  
 __getIframeResponse : function()
 {
   if(this.responseEl){    
     if(this.responseFile){
       if(!this.responseEl.id)this.responseEl.id = "DHTMLSuite_formResponse" + DHTMLSuite.getUniqueId();
       var dynContent = new DHTMLSuite.dynamicContent();
       dynContent.loadContent(this.responseEl.id,this.responseFile);        
     }else{      
       this.responseEl.innerHTML = self.frames[this.iframeName].document.body.innerHTML;  
       this.__evaluateJs(this.responseEl);
       this.__evaluateCss(this.responseEl);  
     }            
   }  
   this.coverDiv.style.display="none";
   this.__handleCallback("onComplete");
 }
 // }}}
 ,
 // {{{ __positionCoverDiv()
   /**
    *  Position cover div
    *
    * @private
    */  
 __positionCoverDiv : function()
 {
   if(!this.responseEl)return;
   try{
     var st = this.coverDiv.style;
     st.left = this.getLeftPos(this.responseEl) + "px";  
     st.top = this.getTopPos(this.responseEl) + "px";  
     st.width = this.responseEl.offsetWidth + "px";  
     st.height = this.responseEl.offsetHeight + "px";  
     st.display="block";
   }catch(e){
   }
 }
 // }}}
 ,
 // {{{ __createCoverDiv()
   /**
    *  Submits the form
    *
    * @private
    */    
 __createCoverDiv : function()
 {  
   if(this.coverDiv)return;
   this.coverDiv = document.createElement("DIV");
   var el = this.coverDiv;
   el.style.overflow="hidden";
   el.style.zIndex = 1000;
   el.style.position = "absolute";
   document.body.appendChild(el);
   
   var innerDiv = document.createElement("DIV");
   innerDiv.style.width="105%";
   innerDiv.style.height="105%";
   innerDiv.className = "DHTMLSuite_formCoverDiv";
   innerDiv.style.opacity = "0.2";
   innerDiv.style.filter = "alpha(opacity=20)";    
   el.appendChild(innerDiv);
   
   var ajaxLoad = document.createElement("DIV");
   ajaxLoad.className = "DHTMLSuite_formCoverDiv_ajaxLoader";
   el.appendChild(ajaxLoad);    
 }
 // }}}
 ,
 // {{{ __createSackObject()
   /**
    *  Create new sack object
    *
    * @private
    */    
 __createSackObject : function(ajaxIndex)
 {    
   var ind = this.objectIndex;
   this.sackObj[ajaxIndex] = new sack();
   this.sackObj[ajaxIndex].requestFile = this.action;  
   this.sackObj[ajaxIndex].method = this.method;    
   this.sackObj[ajaxIndex].onCompletion = function(){ DHTMLSuite.variableStorage.arrayDSObjects[ind].__getResponse(ajaxIndex); }
 }
 // }}}
 ,
 // {{{ __getResponse()
   /**
    *  Get response from ajax
    *
    * @private
    */  
 __getResponse : function(ajaxIndex)
 {
   if(this.responseEl){      
     if(this.responseFile){
       if(!this.responseEl.id)this.responseEl.id = "DHTMLSuite_formResponse" + DHTMLSuite.getUniqueId();
       var dynContent = new DHTMLSuite.dynamicContent();
       dynContent.loadContent(this.responseEl.id,this.responseFile);        
     }else{      
       this.responseEl.innerHTML = this.sackObj[ajaxIndex].response;
       this.__evaluateJs(this.responseEl);
       this.__evaluateCss(this.responseEl);  
     }        
   }  
   
   this.coverDiv.style.display="none";
   this.sackObj[ajaxIndex] = null;
   this.__handleCallback("onComplete");
 }
 ,
 // {{{ isArray()
   /**
    * Return true if element is an array
    *
    * @param Object el = Reference to HTML element
    * @public
    */    
 isArray : function(el)
 {
   if(el.constructor.toString().indexOf("Array") != -1)return true;
   return false;
 }  
 // }}}
 ,
 // {{{ __populateSack()
   /**
    *  Populate sack object with form data
    *  @param ajaxIndex - index of current sack object
    *
    * @private
    */  
 __populateSack : function(ajaxIndex)
 {
   var els = this.formUtil.getValuesAsArray(this.formRef);    
   for(var prop in els){
     if(this.isArray(els[prop])){
       for(var no=0;no<els[prop].length;no++){
         var name = prop + "[" + no + "]";
         if(prop.indexOf("[")>=0){ // The name of the form field is already indicating an array
           name = prop.replace("[","[" + no);  
         }
         this.sackObj[ajaxIndex].setVar(name,els[prop][no]);  
       }
     }else{
       this.sackObj[ajaxIndex].setVar(prop,els[prop]);      
     }      
   }    
 }
 // }}}
 ,
 // {{{ __setInitProperties()
   /**
    *  Fill object with data sent to the constructor
    *  @param Array props - Associative Array("Object") of properties
    *
    * @private
    */    
 __setInitProperties : function(props)
 {
   if(props.formRef)this.formRef = DHTMLSuite.getEl(props.formRef);
   if(props.method)this.method = props.method;
   if(props.responseEl)this.responseEl = DHTMLSuite.getEl(props.responseEl);
   if(props.action)this.action = props.action;
   if(props.responseFile)this.responseFile = props.responseFile;
   if(props.callbackOnComplete)this.callbackOnComplete = props.callbackOnComplete;
   if(!this.action)this.action = this.formRef.action;
   if(!this.method)this.method = this.formRef.method;
 }  
 // }}}
 ,
 // {{{ __handleCallback()
   /**
    *  Execute callback
    *  @param String action - Which callback action
    *
    * @private
    */  
 __handleCallback : function(action)
 {
   var callbackString = "";
   switch(action){
     case "onComplete":
       callbackString = this.callbackOnComplete;
       break;  
     
     
   }  
   if(callbackString){
     if(callbackString.indexOf("(")==-1)callbackString = callbackString + "("" + this.formRef.name + "")";
     eval(callbackString);
   }
   
 }
 ,  
 // {{{ __evaluateJs()
   /**
    * Evaluate Javascript in the inserted content
    *
    * @private
    */  
 __evaluateJs : function(obj)
 {
   obj = DHTMLSuite.getEl(obj);
   
   var scriptTags = obj.getElementsByTagName("SCRIPT");
   var string = "";
   var jsCode = "";
   for(var no=0;no<scriptTags.length;no++){  
     if(scriptTags[no].src){
           var head = document.getElementsByTagName("head")[0];
           var scriptObj = document.createElement("script");
   
           scriptObj.setAttribute("type", "text/javascript");
           scriptObj.setAttribute("src", scriptTags[no].src);    
     }else{
       if(DHTMLSuite.clientInfoObj.isOpera){
         jsCode = jsCode + scriptTags[no].text + "\n";
       }
       else
         jsCode = jsCode + scriptTags[no].innerHTML;  
     }      
   }
   if(jsCode)this.__installScript(jsCode);
 }
 // }}}
 ,
 // {{{ __installScript()
   /**
    *  "Installs" the content of a <script> tag.
    *
    * @private        
    */    
 __installScript : function ( script )
 {    
   try{
       if (!script)
           return;    
         if (window.execScript){          
           window.execScript(script)
         }else if(window.jQuery && jQuery.browser.safari){ // safari detection in jQuery
             window.setTimeout(script,0);
         }else{          
             window.setTimeout( script, 0 );
         } 
   }catch(e){
     
   }
 }  
 // }}}
 ,
 // {{{ __evaluateCss()
   /**
    *  Evaluates css
    *
    * @private        
    */  
 __evaluateCss : function(obj)
 {
   obj = DHTMLSuite.getEl(obj);
   var cssTags = obj.getElementsByTagName("STYLE");
   var head = document.getElementsByTagName("HEAD")[0];
   for(var no=0;no<cssTags.length;no++){
     head.appendChild(cssTags[no]);
   }  
 }  
 // }}}
 ,
 // {{{ getLeftPos()
   /**
    * This method will return the left coordinate(pixel) of an HTML element
    *
    * @param Object el = Reference to HTML element
    * @public
    */  
 getLeftPos : function(el)
 {   
   /*
   if(el.getBoundingClientRect){ // IE
     var box = el.getBoundingClientRect();  
     return (box.left/1 + Math.max(document.body.scrollLeft,document.documentElement.scrollLeft));
   }
   */
   if(document.getBoxObjectFor){
     if(el.tagName!="INPUT" && el.tagName!="SELECT" && el.tagName!="TEXTAREA")return document.getBoxObjectFor(el).x
   }     
   var returnValue = el.offsetLeft;
   while((el = el.offsetParent) != null){
     if(el.tagName!="HTML"){
       returnValue += el.offsetLeft;
       if(document.all)returnValue+=el.clientLeft;
     }
   }
   return returnValue;
 }
 // }}}
 ,
 // {{{ getTopPos()
   /**
    * This method will return the top coordinate(pixel) of an HTML element/tag
    *
    * @param Object el = Reference to HTML element
    * @public
    */  
 getTopPos : function(el)
 {  
   /*
   if(el.getBoundingClientRect){  // IE
     var box = el.getBoundingClientRect();  
     return (box.top/1 + Math.max(document.body.scrollTop,document.documentElement.scrollTop));
   }
   */  
   if(document.getBoxObjectFor){
     if(el.tagName!="INPUT" && el.tagName!="SELECT" && el.tagName!="TEXTAREA")return document.getBoxObjectFor(el).y
   }
   
   var returnValue = el.offsetTop;
   while((el = el.offsetParent) != null){
     if(el.tagName!="HTML"){
       returnValue += (el.offsetTop - el.scrollTop);
       if(document.all)returnValue+=el.clientTop;
     }
   } 
   return returnValue;
 }  
 

} </script>

 <script type="text/javascript">

/* Simple AJAX Code-Kit (SACK) v1.6.1 */ /* �2005 Gregory Wild-Smith */ /* www.twilightuniverse.ru */ /* Software licenced under a modified X11 licence,

  see documentation or authors website for more details */

function sack(file) {

 this.xmlhttp = null;
 this.resetData = function() {
   this.method = "POST";
     this.queryStringSeparator = "?";
   this.argumentSeparator = "&";
   this.URLString = "";
   this.encodeURIString = true;
     this.execute = false;
     this.element = null;
   this.elementObj = null;
   this.requestFile = file;
   this.vars = new Object();
   this.responseStatus = new Array(2);
   };
 this.resetFunctions = function() {
     this.onLoading = function() { };
     this.onLoaded = function() { };
     this.onInteractive = function() { };
     this.onCompletion = function() { };
     this.onError = function() { };
   this.onFail = function() { };
 };
 this.reset = function() {
   this.resetFunctions();
   this.resetData();
 };
 this.createAJAX = function() {
   try {
     this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e1) {
     try {
       this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (e2) {
       this.xmlhttp = null;
     }
   }
   if (! this.xmlhttp) {
     if (typeof XMLHttpRequest != "undefined") {
       this.xmlhttp = new XMLHttpRequest();
     } else {
       this.failed = true;
     }
   }
 };
 this.setVar = function(name, value){
   this.vars[name] = Array(value, false);
 };
 this.encVar = function(name, value, returnvars) {
   if (true == returnvars) {
     return Array(encodeURIComponent(name), encodeURIComponent(value));
   } else {
     this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
   }
 }
 this.processURLString = function(string, encode) {
   encoded = encodeURIComponent(this.argumentSeparator);
   regexp = new RegExp(this.argumentSeparator + "|" + encoded);
   varArray = string.split(regexp);
   for (i = 0; i < varArray.length; i++){
     urlVars = varArray[i].split("=");
     if (true == encode){
       this.encVar(urlVars[0], urlVars[1]);
     } else {
       this.setVar(urlVars[0], urlVars[1]);
     }
   }
 }
 this.createURLString = function(urlstring) {
   if (this.encodeURIString && this.URLString.length) {
     this.processURLString(this.URLString, true);
   }
   if (urlstring) {
     if (this.URLString.length) {
       this.URLString += this.argumentSeparator + urlstring;
     } else {
       this.URLString = urlstring;
     }
   }
   // prevents caching of URLString
   this.setVar("rndval", new Date().getTime());
   urlstringtemp = new Array();
   for (key in this.vars) {
     if (false == this.vars[key][1] && true == this.encodeURIString) {
       encoded = this.encVar(key, this.vars[key][0], true);
       delete this.vars[key];
       this.vars[encoded[0]] = Array(encoded[1], true);
       key = encoded[0];
     }
     urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
   }
   if (urlstring){
     this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
   } else {
     this.URLString += urlstringtemp.join(this.argumentSeparator);
   }
 }
 this.runResponse = function() {
   eval(this.response);
 }
 this.runAJAX = function(urlstring) {
   if (this.failed) {
     this.onFail();
   } else {
     this.createURLString(urlstring);
     if (this.element) {
       this.elementObj = document.getElementById(this.element);
     }
     if (this.xmlhttp) {
       var self = this;
       if (this.method == "GET") {
         totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
         this.xmlhttp.open(this.method, totalurlstring, true);
       } else {
         this.xmlhttp.open(this.method, this.requestFile, true);
         try {
           this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
         } catch (e) { }
       }
       this.xmlhttp.onreadystatechange = function() {
         switch (self.xmlhttp.readyState) {
           case 1:
             self.onLoading();
             break;
           case 2:
             self.onLoaded();
             break;
           case 3:
             self.onInteractive();
             break;
           case 4:
             self.response = self.xmlhttp.responseText;
             self.responseXML = self.xmlhttp.responseXML;
             self.responseStatus[0] = self.xmlhttp.status;
             self.responseStatus[1] = self.xmlhttp.statusText;
             if (self.execute) {
               self.runResponse();
             }
             if (self.elementObj) {
               elemNodeName = self.elementObj.nodeName;
               elemNodeName = elemNodeName.toLowerCase();
               if (elemNodeName == "input"
               || elemNodeName == "select"
               || elemNodeName == "option"
               || elemNodeName == "textarea") {
                 self.elementObj.value = self.response;
               } else {
                 self.elementObj.innerHTML = self.response;
               }
             }
             if (self.responseStatus[0] == "200") {
               self.onCompletion();
             } else {
               self.onError();
             }
             /* These lines were added by Alf Magne Kalleland ref. info on the sack home page. It prevents memory leakage in IE */
             self.URLString = "";
             delete self.xmlhttp["onreadystatechange"];
             self.xmlhttp=null;
             self.responseStatus=null;
             self.response=null;
             self.responseXML=null;
             
             break;
         }
       };
       this.xmlhttp.send(this.URLString);
     }
   }
 };
 this.reset();
 this.createAJAX();

}

 </script>
 <style type="text/css">
 body{
   margin:0px;
   font-size:0.8em;
   font-family:Trebuchet MS
 }
 #mainContainer{
   width:840px;  
   margin:5px;
 }
 table,tr,td{
   vertical-align:top;
 }
 .textInput{
   width:300px;
 }
 html{
   margin:0px;
 }
 .formButton{
   width:75px;
 }
 textarea,input,select{
   font-family:Trebuchet MS;
 }
 i{
   font-size:0.9em;
 }
 </style>

</head> <body>

 <fieldset>
   <legend>Ajax form submit</legend>
 <form action="someplace.html" method="post" name="myForm">
<label for="firstname">First name:</label> <input type="text" class="textInput" name="firstname" id="firstname">
<label for="lastname">Last name:</label> <input type="text" class="textInput" name="lastname" id="lastname">
<label for="address">Address:</label> <textarea class="textInput" name="address"></textarea>
<label for="zipCode">Zip code:</label> <input type="text" name="zipCode" size="10" id="zipCode" minLength="4" maxlength="10">
<label for="age">Age:</label> <input type="text" name="age" id="age" maxlength="3" size="3" minlength="2">
<label for="email">Email:</label> <input class="textInput" type="text" name="email" id="email" maxlength="255">
<label for="url">Url:</label> <input class="textInput" type="text" name="url" id="url" maxlength="255">
<label for="alpha">Alpha chars:</label> <input type="text" class="textInput" id="alpha" name="alpha" maxlength="255">
<label for="custom">Code:</label> <input type="text" class="textInput" id="custom" name="custom" maxlength="255">
<label for="custom">Code 2:</label> <input type="text" class="textInput" id="custom2" name="custom2" maxlength="255">
Country: <select name="country">
         <option value=""></option>
         <option value="NO">Norway</option>
         <option value="DK">Denmark</option>
         <option value="SE">Sweden</option>
         <option value="UK">United Kingdom</option>
         <option value="US">United States</option>
         </select> 
<label for="comments">Comments:</label> <textarea class="textInput" name="comments"></textarea>
Gender:
<input type="radio" name="gender" value="F" id="genderFemale"> <label for="genderFemale"> Female</label> <input type="radio" name="gender" value="M" id="genderMale"> <label for="genderMale"> Male</label>
Hobbies:
         <input type="checkbox" name="hobbies[]" value="games" id="hobby_games"><label for="hobby_games">Computer games</label>
<input type="checkbox" name="hobbies[]" value="soccer" id="hobby_soccer"><label for="hobby_soccer">Soccer</label>
<input type="checkbox" name="hobbies[]" value="stamps" id="hobby_stamps"><label for="hobby_stamps">Stamps</label>
<input type="checkbox" name="hobbies[]" value="shopping" id="hobby_shopping"><label for="hobby_shopping">Shopping</label>
<input type="checkbox" name="agree" id="agree" value="agree"> <label for="agree">I agree</label>
         <input type="button" id="mySubmit" class="formButton" value="Send" onclick="formObj.submit()">
         <input type="reset" class="formButton" value="Reset">
 </form>

<script type="text/javascript"> var formObj = new DHTMLSuite.form({ formRef:"myForm",action:"formSubmit.php",responseEl:"formResponse"}); </script> </body> </html>


 </source>
   
  


form on submit event

   <source lang="html4strict">
  

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> function sendMe() {

   return confirm("Continue?");

} function chkForm() {

   if (form1.textField.value == "")
   {
       alert("Please fill in the text box");
       form1.textField.focus();
       return false;
   }

} </script> </head> <body> <form name="form1" method="POST" action="youtCGI.cgi" onSubmit="return sendMe()">

<input type="text" name="textField"> <input type="submit" value="Submit" onClick="return chkForm()"> <input type="reset" value="Reset">

</form> </body> </html>


 </source>
   
  


Form Submit action

   <source lang="html4strict">
  
   

<html> <body> <script language="JavaScript">

   function function1(){
       document.all.myF.submit();
   }

</script> <form id="myF" method="post" action="yourfile.asp"> Enter your first name: <input type="text"> </form> <input type="button" value="Send the form" onClick="function1();"> </body> </html>



 </source>
   
  


html input mask

<A href="http://www.wbex.ru/Code/JavaScriptDownload/html-input-mask.zip">html-input-mask.zip( 13 k)</a>

1. <A href="/Code/JavaScript/Form-Control/FormSubmitaction.htm">Form Submit action</a> 2. <A href="/Code/JavaScript/Form-Control/Returnthemethodusedwhensendingformdata.htm">Return the method used when sending form data</a> 3. <A href="/Code/JavaScript/Form-Control/SubmitaformViaEnter.htm">Submit a form Via Enter </a> 4. <A href="/Code/JavaScript/Form-Control/ConvertapassedformreferencetoastringformattedlikeaJavaScriptarrayofobjects.htm">Convert a passed form reference to a string formatted like a JavaScript array of objects</a> 5. <A href="/Code/JavaScript/Form-Control/Useformselectcontroltotriggertheaction.htm">Use form select control to trigger the action</a> 6. <A href="/Code/JavaScript/Form-Control/formonsubmitevent.htm">form on submit event</a> 7. <A href="/Code/JavaScript/Form-Control/LastMinuteCheckingBeforeFormSubmission.htm">Last-Minute Checking Before Form Submission</a> 8. <A href="/Code/JavaScript/Form-Control/UseImagetotriggersubmitandresetactions.htm">Use Image to trigger submit and reset actions</a> 9. <A href="/Code/JavaScript/Form-Control/Submitaformbysendingoutanemail.htm">Submit a form by sending out an email</a> 10. <A href="/Code/JavaScript/Form-Control/AdjustingaServerSubmissionAction.htm">Adjusting a Server Submission Action</a> 11. <A href="/Code/JavaScript/Form-Control/DemoAjaxformsubmit.htm">Demo: Ajax form submit</a>

Last-Minute Checking Before Form Submission

   <source lang="html4strict">
  

<html> <head> <title>Validator</title> <script type="text/javascript"> function checkForm(form) {

   for (var i = 0; i < form.elements.length; i++) { 
       if (form.elements[i].type == "text" && form.elements[i].value == "") { 
           document.write("Fill out ALL fields."); 
           return false; 
       } 
   } 
   return true; 

} </script> </head> <body> <form onsubmit="return checkForm(this)"> Please enter all requested information:
First Name:<input type="text" name="firstName">
Last Name:<input type="text" name="lastName">
Rank:<input type="text" name="rank">
Serial Number:<input type="text" name="serialNumber">
<input type="submit"> </form> </body> </html>


 </source>
   
  


Return the method used when sending form data

   <source lang="html4strict">
  

<html> <head> <script type="text/javascript"> function formMethod(){

   var x=document.forms.myForm
   alert(x.method)

} </script> </head> <body>

   <form name="myForm" method="post">
       Name: <input type="text" size="20">
   
<input type="button" onclick="formMethod()" value="Show method"> </form>

</body> </html>



 </source>
   
  


Submit a form by sending out an email

   <source lang="html4strict">
  

<html> <head> <title>Submit and Reset Confirmation</title> <script type="text/javascript"> function allowReset() {

   return window.confirm("Go ahead and clear the form?"); 

} function allowSend() {

   return window.confirm("Go ahead and mail this info?"); 

} </script> </head> <body> <form method="POST" enctype="text/plain" action="mailto:a@b.ru" onreset="return allowReset()" onsubmit="return allowSend()"> Enter your first name: <input type="text" name="firstName" id="firstName"/> Enter your last name: <input type="text" name="lastName" id="lastName"/> Enter your address: <input type="text" name="address" id="address"/> Enter your city: <input type="text" name="city" id="city" /> <input type="radio" name="gender" id="gender1" checked="checked" /> Male <input type="radio" name="gender" id="gender2" />Female <input type="checkbox" name="retired" id="retired" />I am retired <input type="reset" /> <input type="submit" /> </form> </body> </html>


 </source>
   
  


Submit a form Via Enter

   <source lang="html4strict">
  

function submitViaEnter(evt) {

   evt = (evt) ? evt : event;
   var target = (evt.target) ? evt.target : evt.srcElement;
   var form = target.form;
   var charCode = (evt.charCode) ? evt.charCode :
       ((evt.which) ? evt.which : evt.keyCode);
   if (charCode == 13) {
       if (validateForm(form)) {
           form.submit();
           return false;
       }
   }
   return true;

} <input type="text" ... onkeypress="return submitViaEnter(event)">


<form action="..." method="GET" name="sampleForm" onsubmit="return false"> First Name: <input type="text" size="30" name="name1" id="name1"

   onkeypress="return focusNext(this.form, "name2", event)"
   onchange="isNotEmpty(this)" />

Last Name: <input type="text" size="30" name="name2" id="name2"

   onkeypress="return focusNext(this.form, "eMail", event)"
   onchange="isNotEmpty(this)" />

Email Address: <input type="text" size="30" name="eMail" id="eMail"

   onkeypress="return submitViaEnter(event)" />

<input type="reset" /> <input type="button" value="Submit"

   onclick="if (validateForm(this.form)) {this.form.submit( )}" />

</form>



 </source>
   
  


Use form select control to trigger the action

   <source lang="html4strict">
  

<HTML> <BODY> <FORM name="f1"> <SELECT name="s1"> <OPTION SELECTED value="http://www.wbex.ru">wbex.ru <OPTION value="http://www.google.ru">Google <OPTION value="http://www.msn.ru">msn <OPTION value="http://www.perl.ru">Perl.ru <OPTION value="http://www.php.net">Php.net </SELECT> <INPUT type="button" name="go" value="Go!" onClick="window.location=document.f1.s1.options[document.f1.s1.selectedIndex].value"> </FORM>

<FORM name="f2"> <SELECT name="s2" onChange="window.location=document.f2.s2.options[document.f2.s2.selectedIndex].value"> <OPTION SELECTED value="http://www.wbex.ru">wbex.ru <OPTION value="http://www.google.ru">Google <OPTION value="http://www.msn.ru">msn <OPTION value="http://www.perl.ru">Perl.ru <OPTION value="http://www.php.net">Php.net </SELECT> </FORM> </BODY> </HTML> </source>

Use Image to trigger submit and reset actions

   <source lang="html4strict">
  

<html> <head> <title>Registration Form</title> </head> <body> <form name="entries" method="POST" action=""> Enter your first name:<input type="text" name="firstName" id="firstName" />

<p>Enter your last name:<input type="text" name="lastName" id="lastName" />

Enter your address:<input type="text" name="address" id="address" />

Enter your city:<input type="text" name="city" id="city" />

<input type="radio" name="gender" id="gender1" checked="checked"/>Male <input type="radio" name="gender" id="gender2" />Female

<input type="checkbox" name="retired" id="retired" />I am retired

</form>

<a href="javascript:document.forms[0].submit()"> <img alt="image" src="submit.jpg" height="25" width="100" border="0" /></a> <a href="javascript:document.forms[0].reset()"> <img alt="image" src="reset.jpg" height="25" width="100" border="0" /></a>

</body> </html>


 </source>