I am trying to figure out how to submit and capture all form inputs in a dynamically created form on a Handlebar.js template using Underscore.js. This is occurring in a Zendesk custom app.
There is a .hdbs template and app.js file in the scenario. The form loads and shows correctly. The underscore.js function I am using does see the form input but only returns the very first input value/key. It does not return the dynamically generated list of checkboxes.
.hdbs:
<div class="row-fluid">
<p>
</p>
<form id="updateChecklist">
{{listname}}: {{complete}} / {{total}}
<input type="hidden" name="listid" value="{{listid}}">
<br/>
<ul>
{{#each tasks}}
<li class={{fontcolor}}>
<input type="checkbox" name="{{this.id}}" id="{{this.id}}" {{ this.state }}> {{this.name}}
</li>
{{/each}}
</ul>
<button class="btn btn-inverse btn-large" id="update" type="button">Update Tasks</button>
</form>
</div>
app.js:
events: {
'click #update' : 'updateSingleChecklist'
},
...
updateSingleChecklist: function(event) {
var serializedArray = this.$("#updateChecklist").serializeArray();
var itemIdsArray = _.map(serializedArray, function(item, key){
return {item, key};
});
console.log(JSON.stringify(itemIdsArray));
Current Incorrect Result: [{"item":{"name":"listid","value":"56eafe771e9824def46a7d7d"},"key":0}]
What I am looking for is an array of the form inputs, including unchecked checkboxes.
I need:
[{"item":{"name":"listid","value":"56eafe771e9824def46a7d7d"},
{"name":"checkbox1","value":"56eafe771e9824def46a7d8c", "checked":"0"},
{"name":"checkbox2","value":"24eafe771e9824def46a7c6d", "checked":"1"},
{"name":"checkbox3","value":"71eafe771e9824def46a3r5g", "checked":"0"},
...
"key":0}]
It turned out to be lot simpler than I initially realized. The solution to this issue for now is updated at https://jsfiddle.net/sde13q3m/3/ .
Essentially, the map array function with a simple evaluation in the return statement allowed me to collect all form fields and checkboxes for the controller.
var serialized = this.$('#myform input').map(function() {
return { name: this.name, id: this.id, value: this.checked ? "checked" : "false" };
});