form2js icon indicating copy to clipboard operation
form2js copied to clipboard

A way to create an empty list when no checkboxes are selected.

Open jjfine opened this issue 11 years ago • 2 comments

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?

jjfine avatar Apr 24 '13 21:04 jjfine

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...

endeavor85 avatar Aug 25 '14 17:08 endeavor85

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.

stickbyatlas avatar May 06 '15 19:05 stickbyatlas