Hot to get all form elements values using jQuery?

后端 未结 9 1648
谎友^
谎友^ 2020-12-22 23:45

Here is the HTML code:



    HTML Form Builder         


        
9条回答
  •  醉梦人生
    2020-12-23 00:13

    I know you're using jQuery but for those who want a pure Javascript solution:

    // Serialize form fields as URI argument/HTTP POST data
    function serializeForm(form) {
        var kvpairs = [];
        for ( var i = 0; i < form.elements.length; i++ ) {
            var e = form.elements[i];
            if(!e.name || !e.value) continue; // Shortcut, may not be suitable for values = 0 (considered as false)
            switch (e.type) {
                case 'text':
                case 'textarea':
                case 'password':
                case 'hidden':
                    kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
                    break;
                case 'radio':
                case 'checkbox':
                    if (e.checked) kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
                    break;
                /*  To be implemented if needed:
                case 'select-one':
                    ... document.forms[x].elements[y].options[0].selected ...
                    break;
                case 'select-multiple':
                    for (z = 0; z < document.forms[x].elements[y].options.length; z++) {
                        ... document.forms[x].elements[y].options[z].selected ...
                    } */
                    break;
            }
        }
        return kvpairs.join("&");
    }
    

提交回复
热议问题