How to submit unchecked checkbox also

后端 未结 6 1284
滥情空心
滥情空心 2020-12-17 16:56

If checkbox is not checked, clicking on form submit button does not submit any data.

Some checkboxes may be not present in form depending on form fields selected by

6条回答
  •  一向
    一向 (楼主)
    2020-12-17 17:27

    This is a very common problem - when checkbox isn't selected it wont send to server value off/ false by itself. Most popular answer that I found was to add hidden field with the same name as checkbox and value = false. But then when someone checked it it sent me two values.

    And I didn't like it. This is what I did:

    Somewhere in HTML:

    
    

    In JQuery:

    First step is to set hidden values on all checkboxes that aren't checked.

    $(document).ready(function () {
            $(".checkbox").each(function () {
                     if ($(this).prop("checked") == undefined) {
                        $(this).after("")
                     }
                  }
            )
         });
    

    Secondly we have to react on user clicking the check-box: while unselecting add hidden field, when selecting - remove next sibling in DOM - we expected hidden field there.

    WARNING: when check-boxes have common parent you should check if next sibling's type is hidden and then remove it!:

       $(".checkbox").click(function () {
                        if ($(this).prop("checked") == undefined) {
                           $(this).after("")
                        } else {
                           $(this).next().remove();
                        }
                     }
               );
    

    And it works for me :)

提交回复
热议问题