UPDATE
I am looking to limit checkbox selection in specific sections on the same page. To prevent conflicting inputs from different sections, I believe using the label selector
as a separator is the best approach. Each section already has a unique label before the inputs, such as: <label data-addon-name="xxx">
, <label data-addon-name="Options">
, etc. Additionally, each section must have its own checkbox limits.<label data-addon-name="Meats">
Here is the HTML code:
HTML
<div class="wc-pao-addon-container wc-pao-addon wc-pao-addon-opcoes" data-product-name="Lunchbox">
<label for="addon-3913-opcoes-0" class="wc-pao-addon-name" data-addon-name="Options" data-has-per-person-pricing="" data-has-per-block-pricing="">Options </label>
<div class="wc-pao-addon-description"><p>Select up to 5</p>
</div>
<p class="form-row form-row-wide wc-pao-addon-wrap wc-pao-addon-3913-opcoes-0-0">
<label><input type="checkbox" class="wc-pao-addon-field wc-pao-addon-checkbox" name="addon-3913-opcoes-0[]" data-raw-price="" data-price="" data-price-type="quantity_based" value="rice" data-label="Rice"> Rice </label>
</p>
<p class="form-row form-row-wide wc-pao-addon-wrap wc-pao-addon-3913-opcoes-0-1">
<label><input type="checkbox" class="wc-pao-addon-field wc-pao-addon-checkbox" name="addon-3913-opcoes-0[]" data-raw-price="" data-price="" data-price-type="quantity_based" value="bean-broth" data-label="Bean Broth"> Bean Broth </label>
</p>
... (the rest of the HTML content)
<input name="add-to-cart" type="hidden" value="3913"></form>
SCRIPT
$("[data-addon-name='Options'] > input").change(function() {
var max = 2;
if ($("[data-addon-name='Options'] > input:checked").length == max) {
$("[data-addon-name='Options'] > input").attr('disabled', 'disabled');
$("[data-addon-name='Options'] > input:checked").removeAttr('disabled');
} else {
$("[data-addon-name='Options'] > input").removeAttr('disabled');
}
});
Another attempt was utilizing
input[name=addon-3913-opcoes-0[]] ...
since the name is consistent across all selectors, but it resulted in an error in the console. I'm unsure of the significance of []
at the end of the input name, although I suspect it denotes an array format without knowing how to handle it. Ideally, I prefer the first option with the parent selector for easier maintenance, yet I also seek understanding on how to adapt the script to accommodate []
.
Thank you!