Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure that other value is required when other option is selected for radio and checkbox groups #1591

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading