问题
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:
This is my 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>
}
This is my Jquery function
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");
}
Thank you in advance :)
回答1:
I only want one checkbox checked before I submit the page.
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>
}
And in addition to that you could now completely get rid of javascript.
来源:https://stackoverflow.com/questions/11084440/check-uncheck-multiple-checkboxes-with-jquery