jQuery - Dynamic Form Builder
HTML
<label for="formTitle">Form Title </label>
<input type="text" id="formTitle"/>
<button type="button" id="addFormTitle">Add</button>
<table id = "form-gen">
<thead>
<tr>
<th>Field</th>
<th>Type</th>
<th>Width</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fieldName" type="text"></input></td>
<td><input id="fieldType" type="text"></input></td>
<td><input id = "fieldWidth" type="text"></input></td>
<td>
<button type="button" id="btnAdd" >Create</button>
<button type="button" id="btnAddNewRow" >Add to New Row</button>
</td>
</tr>
</tbodY>
</table>
<button type="button" id="btnGetHtml">Get HTML</button>
<div id = "form">
</div>
CSS
.form {
width:600px;
margin: 5px;
border: 1px solid #ddd;
border-radius: 5px 5px 0 0;
}
.form-title {
margin:0;
padding:0;
height:20px;
background-color: #eee;
padding: 5px;
}
.top-curve {
border-radius: 5px 5px 0 0;
}
label, input[type="text"]{
float:left;
display:block;
}
label
{
margin-right: 5px;
margin-left: 5px;
text-align:left;
}
.field{
width:100%;
overflow:auto;
margin:5px 0px;
}
JavaScript
$(function() {
$('label').autoWidth({limitWidth: 350});
$("#addFormTitle").click(function(e) {
addTitle(formTitle.value);
});
$("#btnGetHtml").click(function(e) {
alert($(".form").html());
});
$("#btnAdd").bind("click",function(e) {
var name = $("#fieldName").val();
var type = $("#fieldType").val();
addFields(name, type);
});
$("#btnAddNewRow").bind("click",function(e) {
var name = $("#fieldName").val();
var type = $("#fieldType").val();
addFieldstoNewRow(name, type);
});
});
function addTitle(title) {
var html = '<div class="form"><div class="form-title top-curve">' + title + '</div></div>';
$("#form").append(html);
}
function addFields(name, type) {
var html = '<label for=' + name + '>' + name + '</label>' +
'<input id="' + name + '" type="text" />';
alert(html);
$(".form").append(html);
}
function addFieldstoNewRow(name, type) {
var html = '<div class="field"><label for=' + name + '>' + name + '</label>' +
'<input id="' + name + '" type="text" /></div>';
$(".form").append(html);
}
jQuery.fn.autoWidth = function(options)
{
var settings = {
limitWidth : false
}
if(options) {
jQuery.extend(settings, options);
};
var maxWidth = 0;
this.each(function(){
if ($(this).width() > maxWidth){
if(settings.limitWidth && maxWidth >= settings.limitWidth) {
maxWidth = settings.limitWidth;
} else {
maxWidth = $(this).width();
}
}
});
this.width(maxWidth);
return $(this);
}