I generate a form with the following html dynamically using jquery:
<div id="form_container">
<h1><a>Untitled Form</a></h1>
<form action="save_form" method="post" id="newform" name="newform">
<div class="form_description">
<h2 class="editable">Form title. Click here to edit</h2>
<p class="editable">This is your form description. Click here to edit.</p>
</div>
<ul id="form_body" class="ui-sortable">
<li id="field1" class="world">
<a href="#" onclick="return false;" class="hover">
<label class="editable" for="field1">Text1</label>
<input type="text" name="field1" value="">
</a>
</li>
<li id="field2" class="world">
<a href="#" onclick="return false;" class="hover">
<label class="editable" for="field2">Paragraph2</label>
<textarea cols="" rows="" class="textarea" name="field2"></textarea>
</a>
</li>
<li id="field3" class="world">
<a href="#" onclick="return false;" class="hover">
<label class="editable" for="field3">Label3</label>
<span id="field3">
<input type="radio" id="field31" name="radiogroup" value="1" class="element radio">
<label class="choice editable">option1</label>
<input type="radio" id="field32" name="radiogroup" value="2" class="element radio">
<label class="choice editable">option2</label>
<input type="radio" id="field33" name="radiogroup" value="3" class="element radio">
<label class="choice editable">option3</label>
</span>
</a>
</li>
</ul>
</form>
I would like to serialize metadata about the form to database and recreate it later.
- form title
- form description
Fields:
- field name
- field type
- field_text
- css class (if possible)
I have tried $(‘#newform’).serialize() but it seems to be useful for just getting the name/value pairs of the fields like field1=&field2= and no information about the type of the field.
How do you get no form fields like the header, label etc?
Do I have to get the DOM node for #form_container and look for certain hardcoded values?
Is there a better way to do it?
I am using jquery and rails (2.3.5)
thanks for your help.
Update
Based on Joey’s answer, I came up with the following code that works for me:
$('#newform').find('input').each(function () {
fields.push({
name: $(this).attr('name'),
type: $(this).attr('type'),
text: $(this).val(),
class: $(this).attr('class')
});
var label = $("label[for='" + $(this).attr('name') + "']");
if(label.length != 0) {
fields.push({
name: "label",
type: 'label',
text: label.text(),
class: label.attr('class')
});
}
});
var form = {
title: $('.form_description h2').text(), // or whatever the title is
description: $('.form_description p').text(),
fields: fields
};
console.log(JSON.stringify(form));
You will have to make the object yourself:
Then you could store it (this is just one option of many):
and