【JS】form相关

Form的序列化

function serialize(form){        
    var parts = [],
        field = null,
        i,
        len,
        j,
        optLen,
        option,
        optValue;
    
    for (i=0, len=form.elements.length; i < len; i++){
        field = form.elements[i];
    
        switch(field.type){
            case "select-one":
            case "select-multiple":
            
                if (field.name.length){
                    for (j=0, optLen = field.options.length; j < optLen; j++){
                        option = field.options[j];
                        if (option.selected){
                            optValue = "";
                            if (option.hasAttribute){
                                optValue = (option.hasAttribute("value") ? option.value : option.text);
                            } else {
                                optValue = (option.attributes["value"].specified ? option.value : option.text);
                            }
                            parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
                        }
                    }
                }
                break;
                
            case undefined:     //fieldset
            case "file":        //file input
            case "submit":      //submit button
            case "reset":       //reset button
            case "button":      //custom button
                break;
                
            case "radio":       //radio button
            case "checkbox":    //checkbox
                if (!field.checked){
                    break;
                }
                /* falls through */
                            
            default:
                //don't include form fields without names
                if (field.name.length){
                    parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
                }
        }
    }        
    return parts.join("&");
}

 

对select的操作建议方法:
1、获取option的value的text:selectElement.options[index].text/selectElement.options[index].value

2、设置某选项被选择:selectElement.options[index].selected = true;   //在单选的情况下会取消其他项的选择

3、添加option的最佳方法:

//最佳方案
var newOption = new Option("text","value");
selectElement.add(newOption,undefined);

//效率相对较低,代码编写量大
var newOption = document.createElement("option");
newOption.appendChild(document.createTextNode(textTextbox.value));
newOption.setAttribute("value", valueTextbox.value);
selectElement.appendChild(newOption);

//IE8之前有问题
var newOption = new Option("text","value");
selectElement.appendChild(newOption);

4、移除选项:selectElement.remove(index) 或者 selectElement.removeChild(selectElement.options[index])

5、向select任意位置插入项:selectElement.insertBefore(baseOption,newOption);

 

你可能感兴趣的:(form)