如何实现选中同class的Checkbox时禁用其他未选中的Checkbox?
Solution to Disable Other Checkboxes When One is Selected
Hey there! Let's get this checkbox behavior working correctly. Your current code only grabs the first checkbox with querySelector and doesn't handle disabling the rest—here's how to fix it properly:
Updated JavaScript (Modern Approach)
Instead of using inline onclick attributes, we'll use event listeners for cleaner, more maintainable code:
// Grab all checkboxes with the .checkbox class const checkboxes = document.querySelectorAll(".checkbox"); // Attach a click event to each checkbox checkboxes.forEach(checkbox => { checkbox.addEventListener("click", function() { // Loop through every checkbox to update their state checkboxes.forEach(cb => { // Skip the currently clicked checkbox if (cb !== this) { // Disable others only if the current one is checked; enable them if it's unchecked cb.disabled = this.checked; // Optional: Uncheck other boxes to avoid visual confusion when disabling if (this.checked) { cb.checked = false; } } }); }); });
Updated HTML
We can remove the inline onclick since we're handling events in JavaScript:
<input class="checkbox" type="checkbox"> <input class="checkbox" type="checkbox"> <input class="checkbox" type="checkbox"> <input class="checkbox" type="checkbox">
Key Fixes & Explanations
querySelectorAllinstead ofquerySelector: This grabs all checkboxes with the class, not just the first one.- Event Listeners: Using
addEventListeneris better practice than inlineonclick—it keeps your HTML clean and separates logic from markup. - Boolean
disabledvalue: We usetrue/false(booleans) instead of the string"true"—thedisabledproperty expects a boolean. - Skip the current checkbox: We check if the looped checkbox isn't the one that was clicked, so we never disable the selected box itself.
- Optional uncheck: Adding
cb.checked = falseensures other boxes don't stay checked visually when disabled, which improves user experience.
If You Prefer Inline onclick (Not Recommended)
If you need to keep inline handlers for some reason, modify your code like this:
HTML
<input onclick="check(this)" class="checkbox" type="checkbox"> <input onclick="check(this)" class="checkbox" type="checkbox"> <input onclick="check(this)" class="checkbox" type="checkbox"> <input onclick="check(this)" class="checkbox" type="checkbox">
JavaScript
function check(currentCheckbox) { const allCheckboxes = document.querySelectorAll(".checkbox"); allCheckboxes.forEach(cb => { if (cb !== currentCheckbox) { cb.disabled = currentCheckbox.checked; if (currentCheckbox.checked) { cb.checked = false; } } }); }
内容的提问来源于stack exchange,提问作者Martin Kopečný
相关产品推荐
相关产品推荐

