1

On my page i have a table which includes an 'add row' button, so a user can add more rows if they desire. The row is added by cloning the last row in the table. Within the row I would like to put two checkboxs.

<td class = ''> <input class = '' type='checkbox' name ='installed_by_cm' value='1'/>  </td>
<td class = ''> <input class = '' type='checkbox' name ='installed_after_cm' value='1'/>  </td>

This means that there is multiple checkboxes with the same 'name' tag, something that i require for my data handling later in the code. I use flasks request.form.getlist() to obtain the information in the python backend.

Since the checkbox type default is none and i can not use a hidden input as it will always be collected by the request, I am unable to find a way to make the checkbox send a 1 when checked and a 0 when not checked. Any help would be greatly appriciated.

1
  • You'll need to change the name to an array based one e.g. name="installed_by_cm[]" otherwise the checkboxes will overwrite one each other. Mostly i'd go with an identifier e.g name="installed_by_cm[<?= $id ?>]" (example in PHP) Commented Sep 6, 2019 at 7:37

1 Answer 1

1

Simplest one, no javascript required, just put a hidden input before the checkbox:

<input type="hidden" name="check[0]" value="0" />
<input type="checkbox" name="check[0]" value="1" />

Inputs need to have the same name. If the checkbox is checked then value 1 will be submitted, otherwise value 0 from the hidden input.

Your case javascript solution, no hidden inputs needed:

<script type="text/javascript">
    // when page is ready
    $(document).ready(function() {
         // on form submit
        $("#form").on('submit', function() {
            // to each unchecked checkbox
            $(this + 'input[type=checkbox]:not(:checked)').each(function () {
                // set value 0 and check it
                $(this).attr('checked', true).val(0);
            });
        })
    })
</script>

<form method="post" id="form">
    <input type="checkbox" name="check[0]" value="1" />
    <input type="checkbox" name="check[1]" value="1" />
    <input type="submit" value="Save Changes" />
</form>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.