Skip to main content
2 of 3
added 309 characters in body

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 ifs 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;  

    function combineHTMLCollection(arrayElementNames) {
        var HTMLArray=[];
        for (var i = 0, var elementName = arrayElementNames[i]; i < arrayElementNames.length; i++) {
            elements = form.getElementsByName(elementName);
            for (var j = 0, var element = elements[j]; j < elements.length; j++) {
                HTMLArray.push(element);
            }
        return HTMLArray;
    };

    formElements = combineHTMLCollection(["SELECT", "INPUT","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('&');  
}