Added a method which parses a form and returns a properly encoded post string.

This commit is contained in:
Frank Dillon 2008-09-15 17:18:10 +00:00
parent 847fcfcef3
commit bd24e912c5

View file

@ -50,3 +50,89 @@ WebGUI.Form.toggleAllCheckboxesInForm
*/ */
WebGUI.Form.toggleAllCheckboxesState = {}; WebGUI.Form.toggleAllCheckboxesState = {};
/***********************************************************************************
* @description This method assembles the form label and value pairs and
* constructs an encoded string.
* @method buildQueryString
* @public
* @static
* @param {string || object} form id or name attribute, or form object.
* @param {object} object containing array of form elements to exclude. { id:[], name:[], classNames:[], type:[] }
* @return {string} string of the HTML form field name and value pairs.
*/
WebGUI.Form.buildQueryString = function ( formId, excludes ) {
var _isInArray = function ( value, array) {
if(!array || !value) return 0;
if(typeof array != 'object') return 0;
for(var i = 0; i < array.length; i++) {
if(array[i] == value) return 1;
}
return 0;
};
var oForm = (document.getElementById(formId) || document.forms[formId]);
var oElement, oName, oValue, oDisabled;
var sFormData = "";
if(!excludes) {
excludes = {};
}
// Iterate over the form elements collection to construct the label-value pairs.
for (var i=0; i<oForm.elements.length; i++){
oElement = oForm.elements[i];
oDisabled = oElement.disabled;
oName = oElement.name;
oValue = oElement.value;
oId = oElement.id;
oClass = oElement.className;
oType = oElement.type;
// Do not submit fields that are disabled or do not have a name attribute value.
if(oDisabled || oName == "") continue;
//Filter any excludes passed in
if(_isInArray(oClass,excludes.classNames)) continue;
if(_isInArray(oId,excludes.id)) continue;
if(_isInArray(oName,excludes.name)) continue;
if(_isInArray(oType,excludes.type)) continue;
switch(oType) {
case 'select-one':
case 'select-multiple':
for(var j=0; j<oElement.options.length; j++){
if(oElement.options[j].selected){
if(window.ActiveXObject){
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text) + ";";
}
else{
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text) + ";";
}
}
}
break;
case 'radio':
case 'checkbox':
if(oElement.checked){
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + ";";
}
break;
case 'file':
// stub case as XMLHttpRequest will only send the file path as a string.
case undefined:
// stub case for fieldset element which returns undefined.
case 'reset':
// stub case for input type reset button.
default:
sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + ";";
}
}
sFormData = sFormData.substr(0, sFormData.length - 1);
return sFormData;
};