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

AJAX calls are interrupted due to recursion

On a webpage, I am displaying log files that users can select and delete. The deletion process is carried out through an AJAX request where the ID of each log to be deleted is passed as parameters. However, I have encountered a problem when dealing with a ...

There is no value inputted into the file

I'm facing a small issue while trying to retrieve the value from my input of type="file". Here is the code snippet: <tr ng-repeat="imagenDatos in tableImagenesPunto | filter: busquedaDatosPunto " > <td>PNG</td> <td>{{imag ...

Ways to manage the size of Material-UI vertical tabs?

After receiving assistance from others on the thread about Creating a Material-UI tab with image tabs instead of text labels, I was able to successfully implement images for my Material-UI tabs. However, I am facing an issue where I am unable to control th ...

What is the best method for extracting html-string from html-string across different browsers?

Works perfectly in Chrome and FF, but encountering issues with Safari. var content = '<div><span><p>Can you catch me?</p></span></div>'; content = $.parseXML(content); var span = $(content).find('span&apo ...

Guidelines for choosing a dropdown menu option using jQuery in a WordPress photo gallery

First off, take a look at the screenshot to understand what I'm trying to accomplish: Within WordPress, after clicking on "New Post" and then on the "Add Media" button, a pop-up image gallery appears with an image filtering drop-down menu. My goal is ...

Using AngularJS to Bind HTML Safely: Understanding ngBindHtml and 'unsafe' HTML

I am facing an issue with displaying HTML content containing inline styling in my view. The code I currently have is: <div ng-repeat="snippet in snippets"> <div ng-bind-html="snippet.content"></div> </div> Unfortunately, all of ...

Ways to update the background hue of a selected Navigation Tab?

One of the challenges I am facing in my React Project is with the Navigation Tab from material-ui. The issue I encounter is that the active tab should have a background color, and then revert to its original color when not active. However, the transparency ...

The object you are attempting to use does not have the capability to support the property or method called 'after'

When attempting to add a div tag dynamically using javaScript, I encountered an issue with the .after function not working in IE9+. The error message "SCRIPT438:Object doesn't support property or method 'after'" appeared in the console. If a ...

Why is my jQuery post string null in ASP.NET MVC 2?

There seems to be an issue with passing a constructed string to my Controller Action in JavaScript. Despite setting the data, it appears as null when the action is executed. JavaScript: var xml = "<Request><ZipCode>92612</ZipCode></R ...

Adding a button label value to a FormGroup in Angular

I've been working on a contact form that includes inputs and a dropdown selection. To handle the dropdown, I decided to use the ng-Bootstrap library which involves a button, dropdown menu, and dropdown items. However, I'm facing difficulties inte ...

Promise<IDropdownOption[]> converted to <IDropdownOption[]>

I wrote a function to retrieve field values from my SPFx list: async getFieldOptions(){ const optionDrop: IDropdownOption[]= []; const variable: IEleccion = await sp.web.lists.getByTitle("Groups").fields.getByTitle("Sector").get ...

What is the process for retrieving DOM elements and JavaScript variables using PHP?

I am currently developing a PHP script that will dynamically generate tables in MySQL based on the user's input for the number of columns and column names. However, I have encountered some challenges when trying to access DOM elements and JavaScript v ...

Using Vue.js code on an HTML file is only possible when the necessary CDN is included

Just diving into Vue.js and I've got a header html that doesn't include the cdn link for Vue.js. <nav class="navbar navbar-toggleable-md navbar-inverse"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

What is the best way to retrieve data based on a condition using JavaScript within a React application?

I am struggling to load only a specific number of rows that meet a certain condition. Unfortunately, the current code is fetching all 25 rows and the condition is not being applied correctly. If anyone could provide assistance, it would be greatly apprec ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Tips for personalizing the export grid menu in angular-ui-grid?

My grid includes an external "Show Details" option that adds extra columns to the grid when clicked. The problem arises with the options for "Export all data" and "Export visible data," which can be confusing in this scenario. While I understand that "vi ...

The alignment of the timeline in HTML CSS becomes distorted once it reaches the fourth element

As a newcomer to HTML, CSS, and JS, I am currently embarking on the task of creating a personal website for a course project. One of the pages on my website showcases a timeline featuring dates and information. While I have referred to a tutorial on W3scho ...

Issue encountered with SQL server 2008 due to connection error

My current struggle lies in the connection I am attempting to establish with SQL Server. Unfortunately, whenever I try pressing the period key or entering the server name, I encounter difficulty connecting to SQL Server. ...

Is the order of elements in a CSS file important?

In my situation, I am dealing with a nested list and enclosing div that was created by Drupal's menu system, so I am unable to modify it. My goal is to replicate the menu from a hardcoded website (link removed). How can I include the sub-items (ul l ...