Express body-parser handling checkbox arrays on forms

社会主义新天地 提交于 2019-12-01 21:41:22

My approach requires no javascript on client side. Add hidden fields as many as your checkboxes with same names

body parser will parse checked items as array and string others

I meant

<input type="hidden" name="option[0]" value="0">
<input type="hidden" name="option[1]" value="0">
<input type="hidden" name="option[2]" value="0">
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1">

If your option[1] is checked then body parser will parse it like

{option:['0', ['0', '1'], '0']}

And here is the modifier

req.body.option = req.body.option.map(item => (Array.isArray(item) && item[1]) || null);

so now body will be

{option: [null, '1', null]}

The simplest solution (not the best) is that you can add hidden input's with different ids and then check them when the check-boxes on the page get unchecked.

<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1">

<input type="checkbox" class="hidden" name="hiddenOption[0]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[1]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[2]" value="1">

And before submit:

$('input[name^=option]').each(function () {      
  if(!this.checked) {
    var name = "input[name=\'hiddenOption" + this.name.replace('option', '') + "\']";
    console.log(name);
    $(name).prop('checked', true);
  }
});

And then based on that you can figure out which ones are not ticked.

https://plnkr.co/edit/mJCbtgQnQudHGrUzAz3A?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!