mardi 12 décembre 2017

POST unchecked checkboxes with values to Node

This is a common topic but in this particular use-case I have not been able to find a solution. I have a dynamic number of checkboxes in a form which is being submitted to a Node.js server. My checkboxes look like this:

<input type='checkbox' name='ingredient[num]' checked />

When all checkboxes are checked, the server receives something that looks like this (after req.body.ingredient):

{ num: ['on','on','on'] }

When there are some or all checkboxes unchecked, I want it to receive something like this, with the same number of values:

{num: ['on','off','off'] }

I have tried using a hidden input with value='off' before and after my checkboxes and this hasn't worked. The server receives both 'on' and 'off' values when checked. I've also tried a JavaScript workaround (below) and I haven't gotten it to work. Any ideas?

<script>
let f = document.getElementById('addIngredients');
f.addEventListener('submit', function(e) {
    e.preventDefault();

    let boxes = document.querySelectorAll('input[type=checkbox]:not(:checked)');
    boxes.forEach(function(box) {
        box.setAttribute('value', 'off');
    });

    f.submit();
})




Aucun commentaire:

Enregistrer un commentaire