How can I get form data with JavaScript/jQuery?

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

    showing form input element fields and input file to submit your form without page refresh and grab all values with file include in it here it is

    <form id="imageUploadForm"   action="" method="post" enctype="multipart/form-data">
    <input type="text" class="form-control" id="fname" name='fname' placeholder="First Name" >
    <input type="text" class="form-control" name='lname' id="lname" placeholder="Last Name">
    <input type="number" name='phoneno'  class="form-control" id="phoneno" placeholder="Phone Number">
    <textarea class="form-control" name='address' id="address" rows="5" cols="5" placeholder="Your Address"></textarea>
    <input type="file" name="file" id="file" >
    <input type="submit" id="sub" value="Registration">					   
    </form>
    on Submit button page will send ajax request to your php file.
    $('#imageUploadForm').on('submit',(function(e) 
    {
         fname = $('#fname').val();
         lname =  $('#lname').val();
         address =  $('#address').val();
         phoneno =  $('#phoneno').val();
         file =  $('#file').val();
         e.preventDefault();
         var formData = new FormData(this);
         formData.append('file', $('#file')[0]);
         formData.append('fname',$('#fname').val());
         formData.append('lname',$('#lname').val());
         formData.append('phoneno',$('#phoneno').val());
         formData.append('address',$('#address').val());
         $.ajax({
    		type:'POST',
                    url: "test.php",
                    //url: '<?php echo base_url().'edit_profile/edit_profile2';?>',
    
                    data:formData,
                    cache:false,
                    contentType: false,
                    processData: false,
                    success:function(data)
                    {
                         alert('Data with file are submitted !');
    
                    }
    
         });
    
    }))

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

    For those of you who would prefer an Object as opposed to a serialized string (like the one returned by $(form).serialize(), and a slight improvement on $(form).serializeArray()), feel free to use the code below:

    var Form = {
        _form: null,
        _validate: function(){
            if(!this._form || this._form.tagName.toLowerCase() !== "form") return false;
            if(!this._form.elements.length) return false;
        }, _loopFields: function(callback){
            var elements = this._form.elements;
            for(var i = 0; i < elements.length; i++){
                var element = form.elements[i];
                if(name !== ""){
                    callback(this._valueOfField(element));
                }
            }
        }, _valueOfField: function(element){
            var type = element.type;
            var name = element.name.trim();
            var nodeName = element.nodeName.toLowerCase();
            switch(nodeName){
                case "input":
                    if(type === "radio" || type === "checkbox"){
                        if(element.checked){
                            return element.value;
                        }
                    }
                    return element.value;
                    break;
                case "select":
                    if(type === "select-multiple"){
                        for(var i = 0; i < element.options.length; i++){
                            if(options[i].selected){
                                return element.value;
                            }
                        }
                    }
                    return element.value;
                    break;
                case "button":
                    switch(type){
                        case "reset": 
                        case "submit": 
                        case "button":
                            return element.value;
                            break;
                    }
                    break;
            } 
        }, serialize: function(form){
            var data = {};
            this._form = form;
    
            if(this._validate()){
                this._loopFields(function(value){
                    if(value !== null) data[name] = value;
                });
            }
            return data;
        }
    };
    

    To execute it, just use Form.serialize(form) and the function will return an Object similar to this:

    <!-- { username: "username", password: "password" } !-->
    <input type="text" value="username">
    <input type="password" value="password">
    

    As a bonus, it means you don't have to install the entire bundle of jQuery just for one serialize function.

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

    I wrote a function that takes care of multiple checkboxes and multiple selects. In those cases it returns an array.

    function getFormData(formId) {
        return $('#' + formId).serializeArray().reduce(function (obj, item) {
            var name = item.name,
                value = item.value;
    
            if (obj.hasOwnProperty(name)) {
                if (typeof obj[name] == "string") {
                    obj[name] = [obj[name]];
                    obj[name].push(value);
                } else {
                    obj[name].push(value);
                }
            } else {
                obj[name] = value;
            }
            return obj;
        }, {});
    }
    
    0 讨论(0)
  • 2020-11-22 13:28
    $(form).serializeArray().reduce(function (obj, item) {
          if (obj[item.name]) {
               if ($.isArray(obj[item.name])) {
                   obj[item.name].push(item.value);
               } else {
                    var previousValue = obj[item.name];
                    obj[item.name] = [previousValue, item.value];
               }
          } else {
               obj[item.name] = item.value;
          }
    
         return obj;
    }, {});
    

    It will fix issue:couldn't work with multiselects.

    0 讨论(0)
  • 2020-11-22 13:29
    $("#form input, #form select, #form textarea").each(function() {
     data[theFieldName] = theFieldValue;
    });
    

    other than that, you might want to look at serialize();

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

    I have included the answer to also give back the object required.

    function getFormData(form) {
    var rawJson = form.serializeArray();
    var model = {};
    
    $.map(rawJson, function (n, i) {
        model[n['name']] = n['value'];
    });
    
    return model;
    }
    
    0 讨论(0)
提交回复
热议问题