From 5be52f1a85bad43bb0451243db9828a68584481b Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sat, 27 Apr 2024 13:37:01 +0200 Subject: [PATCH] netteForms: refactoring, added expandRadioElement() --- src/assets/netteForms.js | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/assets/netteForms.js b/src/assets/netteForms.js index aa71fa91..9370e3cb 100644 --- a/src/assets/netteForms.js +++ b/src/assets/netteForms.js @@ -50,6 +50,16 @@ }; + /** + * @param {FormElement} elem + * @return {Array} + */ + let expandRadioElement = function(elem) { + let inputs = elem.form.elements.namedItem(elem.name); + return inputs instanceof RadioNodeList ? Array.from(inputs) : [inputs]; + }; + + /** * Function to execute when the DOM is fully loaded. * @private @@ -76,10 +86,9 @@ return elem[0] ? Nette.getValue(elem[0]) : null; } else if (elem.type === 'radio') { - let elements = elem.form.elements; // prevents problem with name 'item' or 'namedItem' - for (let i = 0; i < elements.length; i++) { - if (elements[i].name === elem.name && elements[i].checked) { - return elements[i].value; + for (let input of expandRadioElement(elem)) { + if (input.checked) { + return input.value; } } return null; @@ -104,12 +113,10 @@ return values; } else if (elem.name && elem.name.endsWith('[]')) { // multiple elements [] - let elements = elem.form.elements[elem.name].tagName ? [elem] : elem.form.elements[elem.name], - values = []; - - for (let i = 0; i < elements.length; i++) { - if (elements[i].type !== 'checkbox' || elements[i].checked) { - values.push(elements[i].value); + let values = []; + for (let input of expandRadioElement(elem)) { + if (input.type !== 'checkbox' || input.checked) { + values.push(input.value); } } return values; @@ -273,8 +280,8 @@ */ Nette.isDisabled = function(elem) { if (elem.type === 'radio') { - for (let i = 0, elements = elem.form.elements; i < elements.length; i++) { - if (elements[i].name === elem.name && !elements[i].disabled) { + for (let input of expandRadioElement(elem)) { + if (!input.disabled) { return false; } } @@ -670,11 +677,10 @@ if ((rule.condition && Nette.toggleControl(elem, rule.rules, curSuccess, firsttime, value, rule.op === ':blank' ? false : emptyOptional)) || rule.toggle) { has = true; if (firsttime) { - let els = elem.form.elements; - for (let i = 0; i < els.length; i++) { - if (els[i].name === curElem.name && !toggleListeners.has(els[i])) { - els[i].addEventListener('change', handler); - toggleListeners.set(els[i], null); + for (let el of expandRadioElement(curElem)) { + if (!toggleListeners.has(el)) { + el.addEventListener('change', handler); + toggleListeners.set(el, null); } } }