Skip to content

Commit

Permalink
update data structure handling - saving grid responses (#3)
Browse files Browse the repository at this point in the history
* update data structure handling - saving grid responses

* cleanup

* fix grid displayif handling
  • Loading branch information
JoeArmani authored Jul 26, 2024
1 parent 2753913 commit 1259daa
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions questionnaire.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,11 +361,18 @@ export function isFirstQuestion() {
return questionQueue.isEmpty() || questionQueue.isFirst();
}

function numberOfInputs(element) {
let resps = Array.from(
element.querySelectorAll("input, textarea, select")
).reduce((acc, current) => {
//if (["submit", "button"].includes(current.type)) return acc;
/**
* Determine the storage format for the response data.
* Grid questions are stored as objects. Ensure each key is stored with the response.
* Single response (radio) input questions are stored as primitives.
* Multi-selection (checkbox) input questions are stored as arrays.
* @param {HTMLElement} form - the form element being evaluated.
* @returns {boolean} - true if the key must be stored with the response (Object), false otherwise (primitive).
*/
function isObjectStore(form) {
if (form.dataset?.grid === 'true') return true;

const responseInputs = Array.from(form.querySelectorAll("input, textarea, select")).reduce((acc, current) => {
if (current.type == "submit" || current.type == "hidden") return acc;
if (["radio", "checkbox"].includes(current.type)) {
acc[current.name] = true;
Expand All @@ -374,24 +381,28 @@ function numberOfInputs(element) {
}
return acc;
}, {});
return Object.keys(resps).length;

return Object.keys(responseInputs).length !== 1;
}

function setFormValue(form, value, id) {
if (value === "") {
value = undefined
if (value === "" || Array.isArray(value) && value.length === 0) {
value = undefined;
}
if (numberOfInputs(form) == 1) {

if (!id || id.trim() === "") return;

if (!isObjectStore(form)) {
form.value = value;
} else {
if (!form.value) {
form.value = {};
}

form.value[id] = value;
if (value == undefined) {
delete form.value[id]
}

}
}

Expand Down Expand Up @@ -1081,8 +1092,11 @@ export function displayQuestion(nextElement) {
console.log(`checking the datagrid for displayif... ${elm.dataset.questionId} ${f}`)

if (f !== true) {
elm.remove();
//elm.closest('tr').remove(); // this is the same as elm.remove()...slower but more flexible. temp leaving in case there are cases I've missed.
elm.dataset.hidden = "true";
elm.style.display = "none";
} else {
delete elm.dataset.hidden;
elm.style.display = "";
}
});

Expand Down

0 comments on commit 1259daa

Please sign in to comment.