Skip to content

Instantly share code, notes, and snippets.

@dwelch2344
Created July 7, 2015 00:58
Show Gist options
  • Save dwelch2344/b95a4340ada46f1ab8ee to your computer and use it in GitHub Desktop.
Save dwelch2344/b95a4340ada46f1ab8ee to your computer and use it in GitHub Desktop.
Iterate some jquery forms?
var addRow = $('.add-row'),
submit = $('.submit'),
container = $('.question-container'),
tpl = $('.template').html() // get the HTML contents as a string
addRow.on('click', addOne);
submit.on('click', sendIt);
// *should* create a whole new element from the string and stuff it in at the bottom
function addOne(){
container.append(tpl);
}
function sendIt(){
var payload = [];
// iterate over our question wrappers
container.find('.form-question-wrap').forEach(function(w){
var obj = {};
// iterate over the question in this wrapper
$(w).find('.form-question').forEach(function(e){
var el = $(e);
obj[el.attr('data-field')] = el.val();
});
// add the object that represents this value to the payload
payload.push(obj);
});
$.post('/endpoint', payload);
}
<script type="text/template">
<div class="form-question-wrap">
<label> Your Name </label>
<input class="form-question" data-field="name">
<br/>
<label> Your Birthday </label>
<input class="form-question" data-field="bday">
<br/>
<label>
<input class="form-question" data-field="isCool" type="checkbox">
Are you cool
</label>
</div>
</script>
<button type="button" class="add-row"> Add a new set of questions </button>
<div class="question-container">
</div>
<button type="button" class="submit"> Send these bad boys out! </button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment