Skip to content

Commit

Permalink
Merge pull request #1591 from lucasnetau/fix/1565
Browse files Browse the repository at this point in the history
fix: ensure that other value is required when other option is selected for radio and checkbox groups
  • Loading branch information
kevinchappell authored Nov 14, 2024
2 parents 7cdc8ac + 457a3e3 commit 978a160
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/js/control/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default class controlSelect extends control {
data.name = data.name + '[]'
}

if (type === 'checkbox-group' && data.required) {
if ((type === 'checkbox-group' || type === 'radio-group') && data.required) {
const self = this
const defaultOnRender = this.onRender.bind(this)
this.onRender = function() {
Expand Down Expand Up @@ -153,7 +153,10 @@ export default class controlSelect extends control {
* setCustomValidity for checkbox-group
*/
groupRequired() {
const checkboxes = this.element.getElementsByTagName('input')
const allInputs = this.element.getElementsByTagName('input')
const checkboxes = this.element.querySelectorAll('input:not([type=text])')
const otherCheckbox = this.element.querySelector('.other-option')
const otherValue = this.element.querySelector('.other-val')
const setValidity = (checkbox, isValid) => {
const minReq = control.mi18n('minSelectionRequired', 1)
if (!isValid) {
Expand All @@ -162,24 +165,32 @@ export default class controlSelect extends control {
checkbox.setCustomValidity('')
}
}
const toggleRequired = (checkboxes, isValid) => {
[].forEach.call(checkboxes, cb => {
const toggleRequired = (checkboxes, otherCheckbox, otherValue, isValid) => {
[].forEach.call(checkboxes, cb => {
if (isValid) {
cb.removeAttribute('required')
} else {
cb.setAttribute('required', 'required')
}
setValidity(cb, isValid)
})

if (otherCheckbox) {
if (otherCheckbox.checked) {
otherValue.setAttribute('required', 'required')
} else {
otherValue.removeAttribute('required')
}
}
}

const toggleValid = () => {
const isValid = [].some.call(checkboxes, cb => cb.checked)
toggleRequired(checkboxes, isValid)
toggleRequired(checkboxes, otherCheckbox, otherValue, isValid)
}

for (let i = checkboxes.length - 1; i >= 0; i--) {
checkboxes[i].addEventListener('change', toggleValid)
for (let i = allInputs.length - 1; i >= 0; i--) {
allInputs[i].addEventListener('change', toggleValid)
}
toggleValid()
}
Expand Down

0 comments on commit 978a160

Please sign in to comment.