Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jjfine opened this issue Apr 24, 2013 · 2 comments
Open

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

jjfine opened this issue Apr 24, 2013 · 2 comments

Comments

@jjfine
Copy link

jjfine commented Apr 24, 2013

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 jjfine closed this as completed Jul 11, 2013
@jjfine jjfine reopened this Jul 11, 2013
@endeavor85
Copy link

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

@stickbyatlas
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants