FormData and checkboxes

前端 未结 2 834
攒了一身酷
攒了一身酷 2021-02-14 05:22

Currently when creating a FormData object, a checked checkbox is added with a value of \"on\", and an unchecked checkbox is not passed at all.

Do I have to

相关标签:
2条回答
  • 2021-02-14 05:51

    Currently when creating a FormData object, a checked checkbox is added with a value of "on", and an unchecked checkbox is not passed at all.

    on is only used if the checkbox is missing a value attribute

    Do I have to hack in some hidden inputs to properly set checkboxes

    No. That is properly handling checkboxes. It is how they have worked in forms since the form element was added to HTML.

    Test for the presence or absence of the checkbox in the code that handles it.

    0 讨论(0)
  • 2021-02-14 06:09

    Try this:

    var checkbox = $("#myForm").find("input[type=checkbox]");
    $.each(checkbox, function(key, val) {
        formData.append($(val).attr('name'), this.is(':checked'))
    });
    

    It always adds the field to FormData with either a value of true when checked, or false when unchecked.

    0 讨论(0)
提交回复
热议问题