本文介绍一种基于 jquery 的动态表单控制方案,通过监听复选框状态变化,自动切换国家组(countries)与产品组(products)的输入类型(checkbox ↔ radio),从而强制满足“1国多品”或“多国1品”的业务约束条件。
在实际数据筛选场景中,常需对多维条件施加逻辑互斥约束:例如,当用户选择多个国家时,只允许选定单一产品;反之,若选择了多个产品,则仅能勾选一个国家。这种“非此即彼、动态降级”的交互模式无法靠静态 HTML 实现,需借助 JavaScript 动态干预 DOM 行为。
核心思路是:不手动禁用/反选控件,而是根据当前选中状态,实时将另一组控件的 type 属性在 checkbox 与 radio 之间切换。因为 radio 天然支持单选约束,且浏览器会自动处理同名 radio 的互斥行为,比手动管理 checked 和 disabled 更健壮、更符合语义。
以下是完整可运行的实现代码:
$(document).ready(function() {
// 绑定所有国家和产品复选框的 change 事件
$('[name^=country], [name^=product]').change(function() {
const $countries = $('[name^=country]');
const $products = $('[name^=product]');
const checkedCountries = $countries.filter(':checked').length;
const checkedProducts = $products.filter(':checked').length;
// 若已选 >1 个国家 → 产品组转为 radio(强制单选)
if (checkedCountries > 1) {
$products.attr('type', 'radio').attr('name', 'product');
} else {
$products.attr('type', 'checkbox').attr('name', 'product[]');
}
// 若已选 >1 个产品 → 国家组转为 radio(强制单选)
if (checkedProducts > 1) {
$countries.attr('type', 'radio').attr('name', 'country');
} else {
$countries.attr('type', 'checkbox').attr('name', 'country[]');
}
});
});✅ 关键优势说明:
⚠️ 注意事项:
该方案以极简逻辑达成强约束交互,兼顾可维护性与用户体验,是表单条件联动的经典轻量解法。