简体   繁体   中英

HTML checkbox select one at a time per group

I've been trying some code to be able to check 1 checkbox at a time, but I also want to be able to check 1 box at a time in another group at the same time ( they work together )

This is the code I've tried so far:

HTML

Checkbox group1

                <div class="modal-body">
                Status to change:
                <br><br>
                <label for=".checkboxSanction">Sanction Status
                    <input type="checkbox" name="statusbox" value="Sanction Status" class="checkboxSanction">
                </label><br>
                <label for=".checkboxPep">Pep Status
                    <input type="checkbox" name="statusbox" value="PEP Status" class="checkboxPep">
                </label><br>
                <label for=".checkboxUnderage">Underage Status
                    <input type="checkbox" name="statusbox" value="Underage Status" class="checkboxUnderage">
                </label><br><br>
                Change status to:

Checkbox group2

                <label for=".checkboxInvestigating">Investigating
                    <input type="checkbox" name="valuebox" value="2" class="checkboxInvestigating">
                </label></br>
                <label for=".checkboxClosed">Closed
                    <input type="checkbox" name="valuebox" value="10" class="checkboxClosed">
                </label>
            </div>

jQuery

    $("input:checkbox").on('click', function () {
    var $box = $(this);
    if ($box.is(":checked")) {
        var group = "input:checkbox[name='" + $box.attr("name") + "']";
        $(group).prop("checked", false);
        $box.prop("checked", true);
    } else {
        $box.prop("checked", false);
    }
});

The problem here is that I can only check 1 box at a time, and that goes for all of the checkboxes ( as in both groups ) - I want to be able to check 1 per group.

Does anyone have an idea of how do solve this issue? Thanks for helping!

Try this

$("input:checkbox").on('click', function() {
    $("input:checkbox[name='"+$(this).attr('name')+"']").not($(this)).prop('checked', false);
});

Same concept as your example just a little more concise.

JSFiddle

EDIT: I've just properly checked your example and it works fine too see here

JSFiddle for your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM