Home:ALL Converter>Generating form from Javascript-Object

Generating form from Javascript-Object

Ask Time:2014-07-29T16:12:36         Author:Manuel Schweigert

Json Formatter

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.

Author:Manuel Schweigert,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/25010875/generating-form-from-javascript-object
user3241019 :

This function creates a form according to the object in parameter :\n\n function makeForm(obj) {\n var form = document.createElement('form');\n form.action=\"/\";\n var input = document.createElement('input');\n input.name = obj.name;\n input.value = obj.value;\n form.appendChild(input);\n document.body.appendChild(form);\n }\n\n\nDEMO",
2014-07-29T08:31:55
Ram :

jQuery itself is dynamic enough for creating DOM elements:\n\nvar $form = $('<form/>', {\n action: '...',\n html: function() {\n return $('<input/>', {\n name: '...',\n value: '...'\n })\n },\n foo: 'bar'\n});\n\n\nYou could also define a constructor according to your requirements, something like:\n\nvar FormMaker = function (options) {\n this.$el = $('<form/>', options.props);\n this.$elements = $.map(options.elements, function (element, i) {\n return $('<' + element.type + '/>', element.props);\n });\n // ...\n this.$el.append(this.$elements);\n return this;\n}\n\nvar form = new FormMaker({\n props: {\n action: 'somewhere',\n method: '...',\n submit: function() {\n console.log('submitted');\n }\n },\n elements: [{\n type: 'input',\n props: {\n type: 'text',\n value: 'aValue',\n // ...\n }\n }, {\n type: 'p',\n props: {\n text: '...'\n }\n }]\n}); \n\nform.$el.appendTo('#somewhere'); \n",
2014-07-29T08:29:20
yy