简体   繁体   中英

Select only one checkbox in a group

I have a lot of the same <div class="checkbox product-option"> , where each four div's do belong to each other.

So 1-4 is a group, 5-8 is a group etc.

Is there a way to allow only 1 checkbox in a group to be selected?

I currently have this code, but that works for all checkbox and not for a group of four.

jQuery:

$('input[type="checkbox"]').on('change', function() {
   $('input[type="checkbox"]').not(this).prop('checked', false);
});

HTML:

<div class="checkbox product-option">
    <label for="addon1">
        <span class="product-option-text">
            <input class="checkbox-row" type="checkbox" name="addons[1]" id="addon1" onclick="prodconfrecalcsummary()">
            <span class="text">Text</span>
        </span>
    </label>
</div>

<div class="checkbox product-option">
    <label for="addon11">
        <span class="product-option-text">
            <input class="checkbox-row" type="checkbox" name="addons[11]" id="addon1" onclick="prodconfrecalcsummary()">
            <span class="text">Text</span>
        </span>
    </label>
</div>

<div class="checkbox product-option">
    <label for="addon12">
        <span class="product-option-text">
            <input class="checkbox-row" type="checkbox" name="addons[21]" id="addon1" onclick="prodconfrecalcsummary()">
            <span class="text">Text</span>
        </span>
    </label>
</div>

<div class="checkbox product-option">
    <label for="addon54">
        <span class="product-option-text">
            <input class="checkbox-row" type="checkbox" name="addons[54]" id="addon1" onclick="prodconfrecalcsummary()">
            <span class="text">Text</span>
        </span>
    </label>
</div>

If you only want one item to be selectable in each group, then you should use radio buttons rather than checkboxes. Then users will expect and understand that only one item is selectable. And if you create a series of radio buttons with the same "name" attribute, then the browser will automatically only allow one of them to be selected.

If you use checkboxes, then even if you use javascript to achieve what you suggest, then your users are likely to be confused, as the normal use of checkboxes is to allow the selection of multiple items at the same time.

您可以使用id进行选择,然后更改您的jquery代码$('#yourIdHere').on('change', function() { //Whatever your code... });

Is this? Put the css selector

$('input[type="checkbox"].checkbox.product-option').on('change', function() {
    $('input[type="checkbox"].checkbox.product-option').not(this).prop('checked', false);
});

Is the same code, but with css selector.

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