Express body-parser handling checkbox arrays on forms

后端 未结 2 1862
轮回少年
轮回少年 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

    
    
    
    
    
    
    

    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]}
    

提交回复
热议问题