'Set value to uncheked checkbox on jquery submit

I have a list of checkboxes inputs that i would like to post even if some of them are not checked. So my idea is to create a hidden input that will get 1 if checked and 0 if not.

Below my jquery code seems like my HiddenInputId variable is not incrementing

        var checkBox = document.getElementsByName('guestCheck[]');
        var HiddenInput = document.getElementsByName('check[]');

        for (var x = 0; x < checkBox.length; x++) {

            var checkBoxId = checkBox[x].id;

            var HiddenInputId = HiddenInput[x].id;


            if ($("#" + checkBoxId + "").is(':checked')) {
                $("#" + HiddenInputId + "").attr('value', '1');

            } else {
                $("#" + HiddenInputId + "").attr('value', '0');
            }

        }




Solution 1:[1]

Make sure that all hidden fields are created, not only just one. HiddenInput return list contains more than one and you can check them without hidden input.

var checkboxes=$("#guestCheck");
for(let i=0; i<checkboxes.length; i++) {
  if(checkboxes[i].checked){
    //perform your post
    break;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sami Ahmed Siddiqui