当单选输入具有不同名称时允许选中一个单选按钮
Allowing one radio button checked when radio inputs have different names
我想弄清楚如何只允许在两个单选按钮不共享相同名称的表单中选中其中一个。我现在已经试验了几个小时,但无法弄清楚。这是我目前拥有的:
$("#theForm").click(function(){
//alert('You clicked radio!');
if($('input:radio:checked')){
$('input:radio:checked').prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="theForm">
<form class="type">
<input type="radio" id="topic" name="topic" value="on" checked>
<input type="radio" id="all" name="all" value="on">
</form>
</div>
这里是 Fiddle:https://jsfiddle.net/Codewalker/reh0mzs3/1/
这应该有效:
<div> <input type="radio" id="contactChoice1" name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2" name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3" name="contact" value="message">
<label for="contactChoice3">Message</label> </div>
点击功能会给你一个事件。您可以定位 event.target.name 以查看单击了哪个单选按钮,然后执行一个简单的 if 语句取消选中另一个单选按钮
$("#theForm").click(function(){
if(event.target.name == 'topic'){
$('#all').prop("checked", false);
}else{
$('#topic').prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="theForm">
<form class="type">
<input type="radio" id="topic" name="topic" value="on" checked>
<input type="radio" id="all" name="all" value="on">
</form>
</div>
我想弄清楚如何只允许在两个单选按钮不共享相同名称的表单中选中其中一个。我现在已经试验了几个小时,但无法弄清楚。这是我目前拥有的:
$("#theForm").click(function(){
//alert('You clicked radio!');
if($('input:radio:checked')){
$('input:radio:checked').prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="theForm">
<form class="type">
<input type="radio" id="topic" name="topic" value="on" checked>
<input type="radio" id="all" name="all" value="on">
</form>
</div>
这里是 Fiddle:https://jsfiddle.net/Codewalker/reh0mzs3/1/
这应该有效:
<div> <input type="radio" id="contactChoice1" name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2" name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3" name="contact" value="message">
<label for="contactChoice3">Message</label> </div>
点击功能会给你一个事件。您可以定位 event.target.name 以查看单击了哪个单选按钮,然后执行一个简单的 if 语句取消选中另一个单选按钮
$("#theForm").click(function(){
if(event.target.name == 'topic'){
$('#all').prop("checked", false);
}else{
$('#topic').prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="theForm">
<form class="type">
<input type="radio" id="topic" name="topic" value="on" checked>
<input type="radio" id="all" name="all" value="on">
</form>
</div>