使用 foreach 从列表中创建复选框(或复选框列表)
Create Checkbox (or checkboxlist) from a list using foreach
我正在尝试从列表中创建一个复选框或复选框列表。我试过了:
@foreach (var bundle in Model.BundleList)
{
<div>
<input type="checkbox" name="labels" value="@bundle.BundleType" id="@bundle.BundleType" />
<label for="@bundle.BundleType">@bundle.BundleType</label>
</div>
}
但是我怎么知道选中了哪个复选框?我还想要单选按钮行为,这意味着只能选择一个复选框。
使用 JQuery 你可以通过 $('input:checkbox:checked')
选择器获得选中的复选框。
并且您可以像下面那样拥有复选框的单选按钮行为。
$("input:checkbox").click(function () {
if (!$(this).is(':checked')) {
$(this).prop('checked', true);
return;
}
$("input:checkbox").not(this).removeAttr("checked");
});
更新:在隐藏字段中设置选中的复选框值。
Html
<input id="SelectedProducts" name="SelectedProducts" type="hidden" />
Jquery
$("input:checkbox").click(function () {
if (!$(this).is(':checked')) {
$(this).prop('checked', true);
return;
}
var checkvalue = $(this).val();
$('#SelectedProducts').val(checkvalue);
$("input:checkbox").not(this).removeAttr("checked");
});
我正在尝试从列表中创建一个复选框或复选框列表。我试过了:
@foreach (var bundle in Model.BundleList)
{
<div>
<input type="checkbox" name="labels" value="@bundle.BundleType" id="@bundle.BundleType" />
<label for="@bundle.BundleType">@bundle.BundleType</label>
</div>
}
但是我怎么知道选中了哪个复选框?我还想要单选按钮行为,这意味着只能选择一个复选框。
使用 JQuery 你可以通过 $('input:checkbox:checked')
选择器获得选中的复选框。
并且您可以像下面那样拥有复选框的单选按钮行为。
$("input:checkbox").click(function () {
if (!$(this).is(':checked')) {
$(this).prop('checked', true);
return;
}
$("input:checkbox").not(this).removeAttr("checked");
});
更新:在隐藏字段中设置选中的复选框值。
Html
<input id="SelectedProducts" name="SelectedProducts" type="hidden" />
Jquery
$("input:checkbox").click(function () {
if (!$(this).is(':checked')) {
$(this).prop('checked', true);
return;
}
var checkvalue = $(this).val();
$('#SelectedProducts').val(checkvalue);
$("input:checkbox").not(this).removeAttr("checked");
});