form2js
form2js copied to clipboard
A way to create an empty list when no checkboxes are selected.
Given the following unselected inputs:
<dl>
<dt>Favorite food</dt>
<dd><label><input type="checkbox" name="person.favFood[]" value="steak"> Steak</label></dd>
<dd><label><input type="checkbox" name="person.favFood[]" value="pizza"> Pizza</label></dd>
<dd><label><input type="checkbox" name="person.favFood[]" value="chicken"> Chicken</label></dd>
</dl>
How could form2js build the following JSON for me?
{ person: { favFood: [] } }
One solution would be to cast a set of square brackets to an empty list. Then you could initialize any list you want to be empty by adding a hidden input as follows:
<dl>
<dt>Favorite food</dt>
<input type="hidden" name="person.favFood" value="[]" />
<dd><label><input type="checkbox" name="person.favFood[]" value="steak"> Steak</label></dd>
<dd><label><input type="checkbox" name="person.favFood[]" value="pizza"> Pizza</label></dd>
<dd><label><input type="checkbox" name="person.favFood[]" value="chicken"> Chicken</label></dd>
</dl>
Any other ideas?
This can be achieved by using the nodeCallback
option:
nodeCallback:function(node){
var name = node.getAttribute ? node.getAttribute('name') : null;
// if the node is named and has the value "[]"
if(name && node.value === "[]")
return { name: name, value: [] }; // change value to empty array
return false;
}
Still wish I didn't have to add the hidden field...
Is there really no better way than doing this? I was wondering why {skipEmpty:false} wasn't picking up an empty set of checkboxes. What a pain.