Employing Jquery for restricting checkbox selection based on parent HTML elements

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

<label data-addon-name="xxx">
as a separator is the best approach. Each section already has a unique label before the inputs, such as:
<label data-addon-name="Options">
,
<label data-addon-name="Meats">
, etc. Additionally, each section must have its own checkbox limits.

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!

Answer №1

Your webpage contains only one label element with the data attribute data-addon-name. There are no descendant elements, particularly an input element descendant. As a result, your JavaScript code does not function correctly. The following revised JavaScript code may work better:

$("div:has([data-addon-name='Opções']) input").change(function() {
  var max = 2;
  if ($("div:has([data-addon-name='Opções']) input:checked").length == max) {
    $("div:has([data-addon-name='Opções']) input").attr('disabled', 'disabled');
    $("div:has([data-addon-name='Opções']) input:checked").removeAttr('disabled');
  } else {
    $("div:has([data-addon-name='Opções']) input").removeAttr('disabled');
  }
});

var max = 2;
    var $inputs = $("div:has([data-addon-name='Opções']) input");
    $inputs.change(function() {
      if($inputs.filter(':checked').length == max) {
        $inputs.attr('disabled', 'disabled');
        $inputs.filter(':checked').removeAttr('disabled');
      } else {
        $inputs.removeAttr('disabled');
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="wc-pao-addon-container  wc-pao-addon wc-pao-addon-opcoes" data-product-name="Marmitex">

        <label for="addon-3913-opcoes-0" class="wc-pao-addon-name" data-addon-name="Opções" data-has-per-person-pricing="" data-has-per-block-pricing="">Opções </label>
        <div class="wc-pao-addon-description">
            <p>Escolha no máximo 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="arroz" data-label="Arroz"> Arroz </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="feijao-caldo" data-label="Feijão Caldo"> Feijão Caldo </label>
        </p>

        (Add remaining checkbox inputs here)

        <div class="clear"></div>
    </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the seamless integration of Material UI slider with chart js

Looking for guidance on syncing Material UI slider with chart js? I'm working on a line chart and hoping to have the x-axis value highlighted with tooltip as I slide the Material UI slider. ...

The map function is not functioning properly following a state update in React

Hey there! I've come across a bit of a dilemma with my map function that I'm using to map a data array within one of the states in my application. Everything seems to be running smoothly upon the initial load, but as soon as I start adding new d ...

The magic of CSS's 3D Transformation feature

Currently, I am working on a 'Flip' effect using the CSS3 transform Property. While everything seems to be functioning properly in recent versions of Chrome, Firefox, and Safari, I'm facing challenges when it comes to creating a fallback fo ...

Trouble detecting browser resize changes

I attempted to create a jQuery function that alerts when the browser is resized, but it doesn't seem to be functioning as expected. http://jsfiddle.net/5m6yG/ function checkBrowserResize(){ var windowHeight = $(window).height(); if ((window ...

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

Executing a Rails Ajax request to communicate with a different controller

I'm new to using Ajax and feeling a bit disoriented. My goal is to call the index method of the company_pays controller from a view managed by the companies controller. I want to replace the div company_content with the data returned from the AJAX req ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Transferring Data to Model

I am attempting to send a variable to the 'GetFiles' function in a model within web2py using this code snippet where the output is saved as 'a': <script> VARIABLE = 'teststring' a = {{=XML(response.json(GetFiles(VARIABL ...

Animate the Bootstrap carousel from top to bottom instead of the traditional left to right movement

Is there an option available in the bootstrap carousel to animate it from top to bottom and bottom to top, rather than from right to left and left to right? jsFiddle link <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval=" ...

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Setting a default value in react-select

Recently, I developed a react-select component that is compatible with redux-form. The SelectInput component looks like this: const MySelect = props => ( <Select {...props} value={props.input.value} onChange={value => props.input.on ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

How to determine if an Angular list has finished rendering

I am facing an issue where I have a large array that is being loaded into a ul list using ng-repeat in Angular. The loading of the list takes too long and I want to display a loader while it's loading, but hide it only when the ul list is fully render ...

Using the getElementById function in javascript to modify CSS properties

Here is the setup I am working with: <div id="admin"> This element has the following style applied to it: display: none; I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript co ...

Tips for accessing the value of an unchecked checkbox in AngularJS

This is a snippet of HTML code: <p> <input type="checkbox" ng-model='add_product.kids' class="filled-in" id="filled-in-box1" /> <label for="filled-in-box1">Kids</label> </p> My goal is to obtain the value "fa ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

Quickest method of writing this (using jQuery)

Is there a more efficient way to accomplish this task in one line? var $d = $('<div>').addClass('clear'); $('.clearAfter').after($d); Alternatively, you can add the CSS style directly using: $('.clearAfter') ...

The box on my form is leaking my background color outside the 1px border, but only in Internet Explorer

While experimenting with background gradients and borders one day just for the fun of it, I made an interesting observation in Internet Explorer. The issue I encountered was that the background color was overflowing outside the radius border, but this onl ...