...

View Full Version : Cleaning up a function



Ultragames
06-13-2007, 09:49 PM
function GetSubmitables( obj ){
url = '';
inputs = obj.getElementsByTagName('INPUT');
selects = obj.getElementsByTagName('SELECT');
textarea = obj.getElementsByTagName('TEXTAREA');
if( inputs.length > 0 ){
for(z=0; z<inputs.length; z++){
if( inputs[z].name.indexOf('[]') >= 0 ){
url += '&'+inputs[z].name.replace('[]','')+'%5B%5D='+escape(inputs[z].value);
} else {
url += '&'+escape(inputs[z].name)+'='+escape(inputs[z].value);
}
}
}
if( selects.length > 0 ){
for(z=0; z<selects.length; z++){
if( selects[z].name.indexOf('[]') >= 0 ){
url += '&'+selects[z].name.replace('[]','')+'%5B%5D='+escape(selects[z].value);
} else {
url += '&'+escape(selects[z].name)+'='+escape(selects[z].value);
}
}
}
if( textarea.length > 0 ){
for(z=0; z<textarea.length; z++){
if( textarea[z].name.indexOf('[]') >= 0 ){
url += '&'+textarea[z].name.replace('[]','')+'%5B%5D='+escape(textarea[z].value);
} else {
url += '&'+escape(textarea[z].name)+'='+escape(textarea[z].value);
}
}
}
return url;
}

This function gets all of the INPUT, SELECT, and TEXTAREA objects inside a given container and adds thier name and value to an AJAX url.

The problem is that the results from getElementsByTagName() is not a true array, and to my knowledge cannot be concatenated, hence requireing the redundant code.

Can someone help me get this all in one loop, or better yet, make getElementsByTagName() get multiple tags, or concat the 3 lists together?

Thank you.

glenngv
06-13-2007, 11:57 PM
You can do it like this:

function GetSubmitables( obj ){
var url = '';
var inputs = obj.getElementsByTagName('INPUT');
var selects = obj.getElementsByTagName('SELECT');
var textarea = obj.getElementsByTagName('TEXTAREA');
url += getParam(inputs);
url += getParam(selects);
url += getParam(textarea);
return url;
}

function getParam(els){
var param="";
for (var z=0; i<els.length; z++){
if( els[z].name.indexOf('[]') >= 0 ){
param += '&'+els[z].name.replace('[]','')+'%5B%5D='+escape(els[z].value);
} else {
param += '&'+escape(els[z].name)+'='+escape(els[z].value);
}
}
return param;
}The code still loops 3 times but the it is more manageable and reusable.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum