gpt4 book ai didi

javascript - 取消选中 Bootstrap 单选按钮

转载 作者:行者123 更新时间:2023-11-30 20:52:52 25 4
gpt4 key购买 nike

我正在尝试取消选中按钮组中用标签包裹的单选按钮,如下所示:

<div>
<label class="btn btn-primary">
<input type="radio" name="radio1" class="radio1" />
Radio1
</label>
</div>
<div>
<label class="btn btn-primary">
<input type="radio" name="radio2" class="radio2" />
Radio2
</label>
</div>
$('.btn').on('click', function(e) {
// Check if another option was previously checked
if ($(this).parent().parent().find(':radio:checked').length == 1) {
inner_input = $(this).find('input');
if (inner_input.prop('checked')) {
e.stopImmediatePropagation();
e.preventDefault();
inner_input.prop('checked', false);
$(this).removeClass('active');
}
});

不幸的是,它不起作用,即使在第二次点击后标签仍然有效。

最佳答案

当前答案中的解决方案适用于 radio 输入。但它不适用于按钮组。为了避免其他搜索者的麻烦,以下代码可能会有所帮助:

$('label').click(function(e) {
e.preventDefault();

var radio = $(this).find('input[type=radio]');

if (radio.is(':checked')) {
e.stopImmediatePropagation();
$(this).removeClass("active");
radio.prop('checked', false);
} else {
radio.prop('checked', true);

}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked>
option 1
</label>
<label class="btn btn-outline-secondary">
<input type="radio" name="options" id="option2" autocomplete="off">
option 2
</label>
<label class="btn btn-outline-secondary">
<input type="radio" name="options" id="option3" autocomplete="off">
option 3
</label>
</div>

关于javascript - 取消选中 Bootstrap 单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47984380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com