How to submit unchecked checkbox also

后端 未结 6 1263
滥情空心
滥情空心 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:28

    My form is created dynamically, so incorporating additional hidden fields would have been quite complicated. For me it works by temporarily altering the field type in a submit handler of the form.

    myForm.addEventHandler("submit", ev => {
        for (let oField of ev.target.elements) {
            if (oField.nodeName.toUpperCase() === "INPUT" &&
                    oField.type === "checkbox" &&
                    ! oField.checked) {
                oField.type = "text";    // input type text will be sent
                             // After submitting, reset type to checkbox
                oReq.addEventListener("loadstart",
                            () => { oField.type = "checkbox"; });
            }
        }
    });
    

    This feels a bit dirty, but works for my.

提交回复
热议问题