Check/uncheck multiple checkboxes with Jquery

北城余情 提交于 2019-12-25 03:52:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!