【发布时间】:2021-12-27 17:12:33
【问题描述】:
我创建了一组复选框,我的目标是选择一个复选框并取消选中另一个复选框。
我已经使用 Stackoverflow 的解决方案成功地实现了这一点。
现在,我正在尝试获取选中复选框的值。这里的主要问题是,当我选择一个复选框时,有时我会得到以前的值而不是当前值。
示例 - 当我单击带有标签 5 的复选框时,我得到 5。然后,我单击 10 有时我得到 10,但通常它显示 5。当我进入下一个 15 时,我之前的值显示为 10 和以此类推。
$("form :input").change(function () {
var checkboxes = $("input[name='" + this.name + "']:checked");
console.log(checkboxes.val());
if (checkboxes) {
$(checkboxes).not(this).prop("checked", false);
}
});
});
<form action="#" method="post">
<div class="cal_box">
<div class="part1">
<div class="bill_input">
<label for="custom_tip">Select Tip %</label>
<div class="tip_btn_group">
<input type="checkbox" name="tip" id="tip5" value="5" />
<label class="btn_box" for="tip5">5%</label>
<input type="checkbox" name="tip" id="tip10" value="10" />
<label class="btn_box" for="tip10">10%</label>
<input type="checkbox" name="tip" id="tip15" value="15" />
<label class="btn_box" for="tip15">15%</label>
<input type="checkbox" name="tip" id="tip25" value="25" />
<label class="btn_box" for="tip25">25%</label>
<input type="checkbox" name="tip" id="tip50" value="50" />
<label class="btn_box" for="tip50">50%</label>
<input
type="text"
name="custom_tip"
id="tip"
value=""
placeholder="Custom"
/>
</div>
</div>
</div>
</div>
</form>
【问题讨论】:
-
您可能需要考虑切换到单选按钮。这可以设置为允许用户仅选择列表中的一项。复选框默认允许用户选中多个项目。
-
UX:您可能希望在“custom_tip”输入之前有另一个复选框来明确设置它自定义 - 否则您的用户可以同时勾选tip5 和 custom_tip - 应该是? (我想您可以像清除复选框一样清除输入)
-
您的小提琴,提供的 (/3/) 缺少
})所以无法运行。 -
@Twisty - 我使用复选框是因为我将有一个重置按钮来重置值并且不想保留任何默认值,这就是为什么不使用单选按钮的原因。
-
Updated fiddle 使用带有重置按钮的收音机。只是为了完整性。