如何获取单选按钮值并清除表中选中的单选按钮
Posted
技术标签:
【中文标题】如何获取单选按钮值并清除表中选中的单选按钮【英文标题】:How to get radio button value and clear checked radio button in table 【发布时间】:2021-06-26 03:06:05 【问题描述】:我正在表格中创建多个单选按钮,使用 Razor 语法(在 ASP.NET Core MVC 下)。
<table class="table table-striped table-hover table-bordered table-sm custom-font">
<thead>
<tr>
<th>Id</th>
<th>Document Name</th>
<th>Signed?</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
<tr>
<td>@item.Id</td>
<td>@item.DocumentName</td>
<td>
@foreach (var sign in item.Signs)
<div class="form-check form-check-inline">
<input type="radio" asp-for="@item.Sign" value="@sign" class="form-check-input" />
<label class="form-check-label">@sign</label>
</div>
<div class="text-center">
<a href="@Url.Action("UpdateSigned", "Document")" class="update" data-id="@item.Id">Update</a> | <a href="#" class="clear">Clear</a>
</div>
</td>
</tr>
</tbody>
</table>
@section Scripts
<script>
$(function ()
$('.update').click(function (e)
e.preventDefault();
var signed = $('input[name="item.Signed"]:checked').val();
alert(signed);
);
$('.clear').click(function (e)
e.preventDefault();
$('.clear input[type="radio"]').prop('checked', false);
);
);
</script>
每行都有更新和清除链接,用于更新记录并清除每行选中的单选按钮。
问题是,从 razor 语法来看,它会为每一行生成具有相同 id 和名称的 html 收音机。所以我无法检查每行的单选并清除选中的单选按钮。
如何解决?
我正在为这种情况在jsfiddle 创建类似的代码。
【问题讨论】:
【参考方案1】:
<input type="radio" asp-for="@item.Sign" value="@sign" class="form-check-input" />
它将为每一行生成具有相同 id 和名称的 html 收音机。
asp-for
属性将为id
和name
html 属性生成并设置值,这会导致问题。
每行都有更新和清除链接,用于更新记录并清除每行选中的单选按钮。
要达到你的要求,你可以试试:
移除asp-for
属性,动态设置默认勾选选项
<input type="radio" name="Sign_for_@item.Id" @(item.Sign==sign? "checked" : "") value="@sign" class="form-check-input" />
修改js代码找到父td
元素,然后找到单选按钮
<script>
$(function ()
$('.update').click(function(e)
e.preventDefault();
var signed = $(this).parent().parent().find('input[type="radio"]:checked').val();
alert(signed);
);
$('.clear').click(function(e)
e.preventDefault();
$(this).parent().parent().find('input[type="radio"]').prop('checked', false);
);
)
</script>
测试结果
【讨论】:
【参考方案2】:您可以使用 for 循环而不是 foreach,并利用索引号为每行创建唯一的 Id。
<table class="table table-striped table-hover table-bordered table-sm custom-font">
<thead>
<tr>
<th>Id</th>
<th>Document Name</th>
<th>Signed?</th>
</tr>
</thead>
<tbody>
@for(int i = 0; i < Model.Count; i++)
var item = Model[i];
<tr>
<td>@item.Id</td>
<td>@item.DocumentName</td>
<td>
@foreach (var sign in item.Signs)
<div class="form-check form-check-inline">
<input type="radio" name="item.Sign@i" id="@item.Sign@i" value="@sign" class="form-check-input" />
<label class="form-check-label">@sign</label>
</div>
<div class="text-center">
<a href="@Url.Action("UpdateSigned", "Document")" class="update" data-id="@item.Id">Update</a> | <a href="#" class="clear">Clear</a>
</div>
</td>
</tr>
</tbody>
您可以在更新和清除按钮上使用 onclick 属性来代替 jquery 事件侦听器,并将行号作为参数传递。但我不确定这是否是正确的解决方案。
【讨论】:
以上是关于如何获取单选按钮值并清除表中选中的单选按钮的主要内容,如果未能解决你的问题,请参考以下文章