我需要使用 jQuery 取消选中已选中的单选按钮。按钮本身是隐藏的,所以我使用点击标签来触发它。到目前为止,我有:
HTML
<form>
<h4>Where would you like to work?</h4>
<div class="radio-holder">
<input id="form1_areas1" name="areas" type="radio" value="area/london">
<label for="form1_areas1">London</label>
</div>
<div class="radio-holder">
<input id="form1_areas2" name="areas" type="radio" value="area/west-midlands">
<label for="form1_areas2">West Midlands</label></div>
</form>
SCSS
form {
max-width: 500px;
margin: 0 auto;
padding-top: 20px;
}
div.radio-holder {
padding: 10px;
}
input[type="radio"] {
display:none;
&:checked+label {
border-bottom: 2px solid #222222;
padding-bottom: 0px;
}
}
JQUERY
$(document).ready(function(){
$("form input[type='radio']:checked + label").click(function(){
$(this).prev().prop( "checked", false );
});
});
这里是 CodePen
但这并不是取消选中单选按钮。我知道这不是单选按钮的标准功能,但我需要用户能够根据需要将单选按钮集恢复到未选中状态,同时还限制它们只能从选项集中选择一个。非常感谢任何帮助。
干杯
迈克
最佳答案
要启用/禁用相同的 radio ,您必须使用 event.preventDefault()
防止默认行为(点击标签时启用复选框,因此选中的属性将始终设置为 true )并以语法方式启用/禁用 radio ,如下面的代码片段所示:
$(document).ready(function(){
$("label").click(function(e){
e.preventDefault();
$check = $(this).prev();
if($check.prop('checked'))
$check.prop( "checked", false );
else
$check.prop( "checked", true );
//console.log($check.prop("checked"));
});
});
form {
max-width: 500px;
margin: 0 auto;
padding-top: 20px;
}
div.radio-holder {
padding: 10px;
}
input[type="radio"] {
display:none;
}
input[type="radio"]:checked+label {
border-bottom: 2px solid #222222;
padding-bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h4>Where would you like to work?</h4>
<div class="radio-holder">
<input id="form1_areas1" name="areas" type="radio" value="area/london">
<label for="form1_areas1">London</label>
</div>
<div class="radio-holder">
<input id="form1_areas2" name="areas" type="radio" value="area/west-midlands">
<label for="form1_areas2">West Midlands</label></div>
</form>
关于javascript - 通过使用 jQuery 单击标签取消选中选中的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47180205/