问题描述
我一直在解决一个较小的jquery问题,这可能只是我尚未看到的一个小问题.我有一个PartialView,我希望能够选中一个复选框,并且应该使所有其他复选框都未选中.在提交页面之前,我只希望选中一个复选框.
I´ve been stuck on a minor jquery problem, it´s probably just something minor I´m not seeing yet. I have a PartialView and I want to be able to check a checkbox and it should make all the other checkboxes unchecked. I only want one checkbox checked before I submit the page.
无论如何,这是我的代码示例:
Anyway, here is my code sample:
这是我的PartialView
@model List<int>
@foreach (var element in Model)
{
<div id="AddedProductImages">
<img src="@Url.Action("RetrieveFile", "File", new { id = element })" alt="@element" width="125px;" />
<input type="checkbox" name="PrimaryImage" onchange="PrimaryImageChkBox('@element')" id="PrimaryCheckbox'@element'"/>
</div>
}
这是我的Jquery函数
我不能先取消选中,然后在第二行告诉选中的复选框吗?
Shouldn´t I be able to uncheck first and then in the second line tell the clicked checkbox to be checked?
function PrimaryImageChkBox(id) {
alert(id);
$('input[name=PrimaryImage]').removeAttr("checked");
$('#PrimaryCheckbox' + id).attr('checked', "checked");
}
预先感谢您:)
推荐答案
这是单选按钮的意思,而不是复选框.您可以使用相同的名称对多个单选按钮进行分组.这样一来,只能同时选择一个单选按钮:
That's what radio buttons are meant for, not checkboxes. You could group multiple radio buttons by using the same name. This allows only a single radio button to be selected at the same time:
@model List<int>
@foreach (var element in Model)
{
<div id="AddedProductImages">
<img src="@Url.Action("RetrieveFile", "File", new { id = element })" alt="@element" width="125px;" />
<input type="radio" name="PrimaryImage" />
</div>
}
此外,您现在可以完全摆脱javascript.
And in addition to that you could now completely get rid of javascript.
这篇关于使用Jquery选中/取消选中多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!