Express body-parser handling checkbox arrays on forms

后端 未结 2 1863
轮回少年
轮回少年 2021-01-20 01:57

I have an HTML form with an array of checkboxes (using [] naming). I need to be able to process this with express. I\'m using body-parser.

相关标签:
2条回答
  • 2021-01-20 02:25

    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]}
    
    0 讨论(0)
  • 2021-01-20 02:29

    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

    0 讨论(0)
提交回复
热议问题