How can I get form data with JavaScript/jQuery?

前端 未结 28 2207
不知归路
不知归路 2020-11-22 12:39

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

For example:



        
28条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 13:25

    Based on neuront's response I created a simple JQuery method that gets the form data in key-value pairs but it works for multi-selects and for array inputs with name='example[]'.

    This is how it is used:

    var form_data = $("#form").getFormObject();
    

    You can find an example below of its definition and how it works.

    // Function start
    $.fn.getFormObject = function() {
        var object = $(this).serializeArray().reduce(function(obj, item) {
            var name = item.name.replace("[]", "");
            if ( typeof obj[name] !== "undefined" ) {
                if ( !Array.isArray(obj[name]) ) {
                    obj[name] = [ obj[name], item.value ];
                } else {
                   obj[name].push(item.value);
                }
            } else {
                obj[name] = item.value;
            }
            return obj;
        }, {});
        return object;
    }
    // Function ends
    
    // This is how it's used
    $("#getObject").click( function() {
      var form_data = $("#form").getFormObject();
      console.log(form_data);
    });
    /* Only to make view better ;) */
    #getObject {
      padding: 10px;
      cursor:pointer;
      background:#0098EE;
      color:white;
      display:inline-block;
    }
    
    
    Get object (check the console!)

提交回复
热议问题