简体   繁体   中英

Generating form from Javascript-Object

I am looking for a way to generate an html form from JavaScript data dynamically to send a regular post request instead of an Ajax call. This seems to be a somewhat rare use-case as I only find results for Form->JSON.

I am looking to do this:

var form = $('<form Action="/"><Input type="hidden" Name="data" value="5"/></form>');
form.appendTo($("body")).submit();

Just dynamically with data from a JavaScript object, hypothetical example:

var form = $.createForm({ action: "/", data: myData });    
form.appendTo($("body")).submit();

Are there any jQuery plugins or JS snippets which would generate the form?

Update : myData of course is a complex object, not one or two form fields, hence why I want to automate it. Right now I am serializing the data to json and posting it like described, but I would like to send the data properly.

Update 2 : I am looking to do something along the lines of $.deserialize, just that the function should generate the necessary form, not just fill an existing one.

jQuery itself is dynamic enough for creating DOM elements:

var $form = $('<form/>', {
   action: '...',
   html: function() {
       return $('<input/>', {
          name: '...',
          value: '...'
       })
   },
   foo: 'bar'
});

You could also define a constructor according to your requirements, something like:

var FormMaker = function (options) {
    this.$el = $('<form/>', options.props);
    this.$elements = $.map(options.elements, function (element, i) {
        return $('<' + element.type + '/>', element.props);
    });
    // ...
    this.$el.append(this.$elements);
    return this;
}

var form = new FormMaker({
    props: {
        action: 'somewhere',
        method: '...',
        submit: function() {
           console.log('submitted');
        }
    },
    elements: [{
        type: 'input',
        props: {
            type: 'text',
            value: 'aValue',
            // ...
        }
    }, {
        type: 'p',
        props: {
            text: '...'
        }
    }]
}); 

form.$el.appendTo('#somewhere');     

This function creates a form according to the object in parameter :

 function makeForm(obj) {
        var form = document.createElement('form');
        form.action="/";
        var input = document.createElement('input');
        input.name = obj.name;
        input.value = obj.value;
        form.appendChild(input);
        document.body.appendChild(form);
    }

DEMO

May I humbly suggest Metawidget ?

It generates HTML forms from arbitrary complex JSON objects. Simple JavaScript example:

<!DOCTYPE HTML>
<html>
   <head>
      <script src="http://metawidget.org/js/4.0/metawidget-core.min.js"></script>
      <style>
         #metawidget {
            border: 1px solid #cccccc;
            width: 250px;
            border-radius: 10px;
            padding: 10px;
            margin: 50px auto;
         }
      </style>
   </head>
   <body>
      <div id="metawidget"></div>
      <script type="text/javascript">
         var mw = new metawidget.Metawidget( document.getElementById( 'metawidget' ));
         mw.toInspect = {
            firstname: 'Homer',
            surname: 'Simpson',
            age: 36
         };
         mw.buildWidgets();
      </script>
   </body>
</html>

It also supports:

  • augmenting the JSON object with additional sources of metadata, such as JSON Schema or metadata from REST services
  • frameworks such as JQuery UI, JQuery Mobile, AngularJS
  • third-party component libraries
  • pluggable layouts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM