From e48d1224f6d18d7b9bf52364c3bddda25f39a082 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Sat, 28 Dec 2024 00:19:22 +0100 Subject: [PATCH] Improve validate_form() JS helper function --- static/js/app.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/static/js/app.js b/static/js/app.js index 585cf95..255742d 100644 --- a/static/js/app.js +++ b/static/js/app.js @@ -127,9 +127,10 @@ function show_form_modal(opts) { /** * Validate and serialize form's data * @param {jQuery} form The form element to validate and serialize + * @param {bool} keep_empty Keep element with empty value in result (optional, default: false) * @returns object|false The serialized form's data on success or false */ -function validate_form(form) { +function validate_form(form, keep_empty = false) { form.find(".is-invalid").removeClass("is-invalid"); if (!form[0].checkValidity()) { $(form[0].elements).each(function (idx, element) { @@ -140,7 +141,12 @@ function validate_form(form) { var data = {}; jQuery.each(form.serializeArray(), function (idx, item) { item.value = item.value.trim(); - if (item.value) data[item.name] = item.value; + if (item.value || keep_empty) data[item.name] = item.value; + }); + form.find("input[type=checkbox]").each(function (idx, checkbox) { + if (!$(checkbox).val() && $(checkbox).attr("name")) { + data[$(checkbox).attr("name")] = $(checkbox).is(":checked"); + } }); console.log(data); return data;