In regards to variables i
and j
they are loop index variables and can be declared in the loop alone instead of at the top. It will clean up the code.
Example
for (var j=0;j<obj.length;++j){...}
Personally I would write it up like this describing p
and i
which are form elements. In additon there is no need to duplicate code (example would be 3 identical for statments), you can gather all the form elements and concat the arrays together in one. Then by using a switch statement you can minimize the duplicate if
s for each element type and eliminate the need for duplicate for statements. Have a look below. it is much cleaner.
function test_submit(id){
var params=[],
results=[],
form=document.getElementById(id),
formElements,
obj;
formElements = form.getElementsByTagName('SELECT');
formElements = formElements.concat(form.getElementsByTagName('input'));
formElements = formElements.concat(form.getElementsByTagName('textarea'));
for(var i = 0, var formElement = formElements[i]; i < formElements.length; i++) {
if (formElement.name) {
switch (formElement.tagName) {
case "SELECT":
for(var j=0, var optionItem = formElement.options[j]; j < formElement.length; j++){
if(optionItem.selected){
var value = optionItem.value;
if(!value) value = optionItem.text;
params.push([formElement.name,value]);
}
}
break;
case "INPUT":
var type=formElement.type,
value=formElement.value;
if(type) type=type.toLowerCase();
if(type && (type == 'radio' || type == 'checkbox')) {
if(formElement.checked) params.push([formElement.name,value?value:'on']);
}
else params.push([formElement.name,value]);
break;
case "TEXTAREA":
params.push([formElement.name,formElement.value]);
break;
}
}
}
for (var i in params) results.push(params[i][0]+'='+escape(params[i][1]));
return results.join('&');
}