please tell me how to make an analogue of radio inputs with a checkbox? To be able to select only one input
<input type="checkbox" name="subcategory">
<input type="checkbox" name="subcategory">
<input type="checkbox" name="subcategory">
<input type="checkbox" name="subcategory">
const inputs = document.querySelectorAll('input[name="subcategory"]');
inputs.forEach((item) => {
item.addEventListener('click', () => {
item.checked = false;
});
});
>Solution :
If you want to make checkboxes "feel like" radio groups, you will need to do a few things.
- Add a data attribute to the checkboxes to enable single-checked mode i.e.
data-check-radio - Ensure that the input names end in square brackets i.e.
name="subcategory[]" - Assign unique values to each input
I have created a helper function below that can be re-used:
// Reusable function
function CheckRadioHelper(dataProperty) {
dataProperty = dataProperty || 'checkRadio';
window.addEventListener('change', function (event) {
if (
event.target.tagName === 'INPUT' &&
event.target.type === 'checkbox' &&
(
(
event.target.dataset &&
event.target.dataset.hasOwnProperty(dataProperty)
) ||
event.target.hasAttribute(`data-${toKebabCase(dataProperty)}`)
)
) {
document.querySelectorAll(`input[name="${event.target.name}"]`)
.forEach(function(sibling) {
if (sibling.value !== event.target.value) {
sibling.checked = false;
}
});
}
});
}
CheckRadioHelper(); // Now, call it
// Source: https://stackoverflow.com/a/67243723/1762224
function toKebabCase(str) {
return str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, function(match, offset) {
return (offset ? '-' : '') + match.toLowerCase();
});
}
<input data-check-radio type="checkbox" name="subcategory[]" value="1" />
<input data-check-radio type="checkbox" name="subcategory[]" value="2" />
<input data-check-radio type="checkbox" name="subcategory[]" value="3" />
<input data-check-radio type="checkbox" name="subcategory[]" value="4" />
Note: I added a toKebabCase method in case Element.prototype.dataset does not exist. It falls back to using an attribute check.
Here is an ES6 version that is simplified:
// Reusable function
const CheckRadioHelper = (dataProperty = 'checkRadio') => {
window.addEventListener('change', ({ target }) => {
if (
target.tagName === 'INPUT' &&
target.type === 'checkbox' &&
target.dataset.hasOwnProperty(dataProperty)
) {
document.querySelectorAll(`input[name="${target.name}"]`)
.forEach((sibling) => {
if (sibling.value !== target.value) {
sibling.checked = false;
}
});
}
});
}
CheckRadioHelper(); // Now, call it
<input data-check-radio type="checkbox" name="subcategory[]" value="1" />
<input data-check-radio type="checkbox" name="subcategory[]" value="2" />
<input data-check-radio type="checkbox" name="subcategory[]" value="3" />
<input data-check-radio type="checkbox" name="subcategory[]" value="4" />