How can I get form data with JavaScript/jQuery?

前端 未结 28 1924
不知归路
不知归路 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:23

    you can use this function for have an object or a JSON from form.

    for use it:

    var object = formService.getObjectFormFields("#idform");

     function  getObjectFormFields(formSelector)
            {
                /// <summary>Função que retorna objeto com base nas propriedades name dos elementos do formulário.</summary>
                /// <param name="formSelector" type="String">Seletor do formulário</param>
    
                var form = $(formSelector);
    
                var result = {};
                var arrayAuxiliar = [];
                form.find(":input:text").each(function (index, element)
                {
                    var name = $(element).attr('name');
    
                    var value = $(element).val();
                    result[name] = value;
                });
    
                form.find(":input[type=hidden]").each(function (index, element)
                {
                    var name = $(element).attr('name');
                    var value = $(element).val();
                    result[name] = value;
                });
    
    
                form.find(":input:checked").each(function (index, element)
                {
                    var name;
                    var value;
                    if ($(this).attr("type") == "radio")
                    {
                        name = $(element).attr('name');
                        value = $(element).val();
                        result[name] = value;
                    }
                    else if ($(this).attr("type") == "checkbox")
                    {
                        name = $(element).attr('name');
                        value = $(element).val();
                        if (result[name])
                        {
                            if (Array.isArray(result[name]))
                            {
                                result[name].push(value);
                            } else
                            {
                                var aux = result[name];
                                result[name] = [];
                                result[name].push(aux);
                                result[name].push(value);
                            }
    
                        } else
                        {
                            result[name] = [];
                            result[name].push(value);
                        }
                    }
    
                });
    
                form.find("select option:selected").each(function (index, element)
                {
                    var name = $(element).parent().attr('name');
                    var value = $(element).val();
                    result[name] = value;
    
                });
    
                arrayAuxiliar = [];
                form.find("checkbox:checked").each(function (index, element)
                {
                    var name = $(element).attr('name');
                    var value = $(element).val();
                    result[name] = arrayAuxiliar.push(value);
                });
    
                form.find("textarea").each(function (index, element)
                {
                    var name = $(element).attr('name');
                    var value = $(element).val();
                    result[name] = value;
                });
    
                return result;
            }

    0 讨论(0)
  • 2020-11-22 13:24
    var formData = new FormData($('#form-id'));
    params   = $('#form-id').serializeArray();
    
    $.each(params, function(i, val) {
        formData.append(val.name, val.value);
    });
    
    0 讨论(0)
  • 2020-11-22 13:25

    If you are using jQuery, here is a little function that will do what you are looking for.

    First, add an ID to your form (unless it is the only form on the page, then you can just use 'form' as the dom query)

    <form id="some-form">
     <input type="radio" name="foo" value="1" checked="checked" />
     <input type="radio" name="foo" value="0" />
     <input name="bar" value="xxx" />
     <select name="this">
      <option value="hi" selected="selected">Hi</option>
      <option value="ho">Ho</option>
    </form>
    
    <script>
    //read in a form's data and convert it to a key:value object
    function getFormData(dom_query){
        var out = {};
        var s_data = $(dom_query).serializeArray();
        //transform into simple data/value object
        for(var i = 0; i<s_data.length; i++){
            var record = s_data[i];
            out[record.name] = record.value;
        }
        return out;
    }
    
    console.log(getFormData('#some-form'));
    </script>
    

    The output would look like:

    {
     "foo": "1",
     "bar": "xxx",
     "this": "hi"
    }
    
    0 讨论(0)
  • 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;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <form id="form">
      <input type="text" name="text" value="Hola amigo" /> 
      
      <input type="text" name="text_array[]" value="Array 1" /> 
      <input type="text" name="text_array[]" value="Array 2" /> 
      <input type="text" name="text_array[]" value="Array 3" /> 
      
      <select name="multiselect" multiple>
        <option name="option1" selected> option 1 </option>
        <option name="option2" selected> option 2 </option>
      </select>
      
      <input type="checkbox" name="checkbox" value="checkbox1" checked/>
      <input type="checkbox" name="checkbox" value="checkbox2" checked/>
      
      <input type="radio" name="radio" value="radio1" checked/>
      <input type="radio" name="radio" value="radio2"/>
    
    </form>
    
    <div id="getObject"> Get object (check the console!) </div>

    0 讨论(0)
  • 2020-11-22 13:26

    I use this:

    jQuery Plugin

    (function($){
      $.fn.getFormData = function(){
        var data = {};
        var dataArray = $(this).serializeArray();
        for(var i=0;i<dataArray.length;i++){
          data[dataArray[i].name] = dataArray[i].value;
        }
        return data;
      }
    })(jQuery);
    

    HTML Form

    <form id='myform'>
      <input name='myVar1' />
      <input name='myVar2' />
    </form>
    

    Get the Data

    var myData = $("#myForm").getFormData();
    
    0 讨论(0)
  • 2020-11-22 13:26

    $( "form" ).bind( "submit", function(e) {
        e.preventDefault();
        
        console.log(  $(this).serializeObject() );    
    
        //console.log(  $(this).serialize() );
        //console.log(  $(this).serializeArray() );
    
    });
    
    
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
    
        $.each( a, function() {
            if ( o[this.name] !== undefined) 
            {
                if ( ! o[this.name].push ) 
                {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            }
            else 
            {
                o[this.name] = this.value || '';
            }
        });
    
        return o;
    };
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <form>
    
        <input type="radio" name="foo" value="1" checked="checked" />
        <input type="radio" name="foo" value="0" />
        <input name="bar" value="xxx" />
    
        <select name="this">
            <option value="hi" selected="selected">Hi</option>
            <option value="ho">Ho</option>
        </select>
    
        <input type="submit" value="Submit" />
    
    </form>

    Codepen

    0 讨论(0)
提交回复
热议问题