Reputation: 4974
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.
Upvotes: 0
Views: 338
Reputation: 1325
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:
Upvotes: 0
Reputation: 144689
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');
Upvotes: 1
Reputation: 811
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);
}
Upvotes: 0