我无法使输入
名称相同或值相同。第二个和第三个输入来自使用 c#
razor 的循环。我有 2 组 radio 输入,第一组是一组,第二组和第三组是另一组。因为第二个和第三个具有相同的名称,所以选中一个会使另一个不选中。我希望所有这些都一样,所以就像我有一组 3 个单选按钮一样。正如我上面所说,由于后端数据显示问题,我无法使名称或值相同。下面是我的尝试。
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="@Model.Facet.Key" value="@item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="@Model.Facet.Key" value="@item.Key" />tagItem.Name
</label>
</div>
<script>
$(document).ready(function () {
if ($('#dcenter-listradio').prop("checked", true)) {
$('#dcenter-allradio').prop("checked", false);
}
if ($('#dcenter-allradio').prop("checked", true)) {
$('#dcenter-listradio').prop("checked", false);
}
});
</script>
最佳答案
如果您可以为它们提供相同的类,那么您可以使用 jQuery 来检测何时发生更改,然后取消选中同一类中的其他项目。
$(document).ready(function() {
var selector = ".groupTogether";
// or if you can't give same class, you could use "#unrelatedRadio, input[name='related']"
$(selector).change(function()
{
if(this.checked)
{
$(selector).not(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="unrelatedRadio" name="unrelated" type="radio" class="groupTogether">unrelated</input>
<input id="relatedA" name="related" type="radio" class="groupTogether">Related A</input>
<input id="relatedB" name="related" type="radio" class="groupTogether">Related B</input>
或者,如果您不能为它们提供相同的类,只需将选择器替换为选择两个集合的内容即可(在我的示例中,"#unlatedRadio, input[name='related']"
)
关于javascript - 使复选框成为一组单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46981155/