Identify the specific code that will be executed upon pressing a button - checkbox restriction

Check out my code example on jsfiddle: https://jsfiddle.net/elenderg/wzarrg06/63/

In the first div, there are 10 buttons. See image below: https://i.sstatic.net/BDdtG.png

    <button class='btn btn-info custom' onclick="myFunction()">6 (R$ 2,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">7 (R$ 5,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">8 (R$ 10,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">9 (R$ 20,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">10 (R$ 50,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">11 (R$ 100,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">12 (R$ 250,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">13 (R$ 500,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">14 (R$ 1000,00)</button>
    <button class='btn btn-info custom' onclick="myFunction()">15 (R$ 2000,00)</button>

By clicking on one of these buttons, users will be restricted to select a specific number of checkboxes in div #2 For instance, if they click on the "6" button, they can only check up to 6 checkboxes. https://i.sstatic.net/tUYsd.png

I'm looking for a JavaScript or jQuery solution to enforce this limitation on checkbox selection based on the button clicked.

Answer №1

Implementing this feature in jQuery is quite simple. Below is a basic example to help you understand:

HTML:

 <div class="limits">
    <input type="button" value="Three" data-value="3">
    <input type="button" value="Four" data-value="4">
    <input type="button" value="Five" data-value="5">
<div>

<div class="checks">
    <input type="checkbox" name=“check” id="check1" value="1" />
    <label for="check1">1</label>
    <input type="checkbox" name=“check” id="check2" value="2" />
    <label for="check2">2</label>
    <input type="checkbox" name=“check” id="check3" value="3" />
    <label for="check3">3</label>
    <input type="checkbox" name=“check” id="check4" value="4" />
    <label for="check4">4</label>
    <input type="checkbox" name=“check” id="check5" value="5" />
    <label for="check5">5</label>
</div>

JS:

(function($){

    var currentLimit=3;

    $('div.limits > input[type=button]').on('click',function(){
      currentLimit = parseInt($(this).data('value'));
    });

    $('div.checks input').on('click', function(e){
        var totalChecked = $('input:checked').length;

        if (totalChecked > currentLimit){
            e.preventDefault();
        }
    });

})(jQuery)

Feel free to check out the working example here: http://jsfiddle.net/jh5wtzaf/

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

Error in Typescript for the prop types of a stateless React component

When reviewing my project, I came across the following lines of code that are causing a Typescript error: export const MaskedField = asField(({ fieldState, fieldApi, ...props }) => { const {value} = fieldState; const {setValue, set ...

Trouble with executing asynchronous AJAX request using when() and then() functions

Here is the code that I am currently using: function accessControl(userId) { return $.ajax({ url: "userwidgets", type: "get", dataType: 'json', data: { userid: userId } }); }; var user ...

Opening an Accordion programmatically in an Angular 4 application

I am currently developing an Angular 4 application where I have implemented the same accordion feature in two different components. My goal is to allow the user to click on an accordion in the first component and then pass the selected index to the second ...

Executing a Google Script will result in a newly inserted column automatically adopting the

My coding issue involves a simple scenario where cell A1 contains a date, for example 06/06/2017. What I aim to do is add three columns and apply formulas to them. I insert columns using the following code: ss.insertColumns(1,3); Subsequently, I set for ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

Exploring Problems with Implementing the Jquery .click() Function on a Class

My goal is to create a simple JQuery code that triggers a pop-up message saying hello when any element of the specified class is clicked. Here's what I've tried: $(document).ready(function(){ $(".thumb_radio").click(function(){ aler ...

Enhancing performance by implementing cache mechanism for storing search results in a table with multiple filtering options using Vue

In my current project, I am utilizing VueJS. However, the issue I am facing is not necessarily exclusive to this framework - but if there is a vue-specific solution available, that would be my preference. The task at hand involves constructing a table wit ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

I'm struggling to incorporate the JQuery slideDown function into my code. Can someone lend a hand?

Why isn't the video div sliding down and displaying properly in the beginning? Any ideas on how to fix it? Here is the snippet of HTML code and JavaScript: <!DOCTYPE HTML> <html> <head> <title>Team Songs</title> <link ...

Having trouble displaying the desired formatting when mapping through nested JSON in Node ES6

Currently working on a project to build a photo gallery using nested JSON data. My goal is to iterate through the data and create a well-structured JavaScript object or a smaller JSON file that includes only the text and image URL nodes. However, my curren ...

Variability in the values returned by the useState hook

Currently, I am working on developing my initial user signup form, and I have encountered a challenge that seems relatively simple to resolve but goes beyond my current expertise. The issue pertains to the helperText for an MUI select component which is no ...

Submitting form data via Ajax without refreshing the page

I am trying to submit my form using Ajax without refreshing the page. However, it seems that the $_POST values are not being picked up. I don't receive any errors, but I suspect that my form is not submitting correctly. HTML Form <form action="" ...

What are the steps to transform a blob into an xlsx or csv file?

An interesting feature of the application is the ability to download files in various formats such as xlsx, csv, and dat. To implement this, I have utilized a library called fileSaver.js. While everything works smoothly for the dat/csv format, there seems ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

leveraging AJAX to showcase information retrieved from a MySQL database

Hello! I am brand new to PHP and have little knowledge of AJAX. I am in the process of creating a photo gallery site and have used the following code to display my photos. I would like to make it possible, using AJAX or any other language, for someone to c ...

Tips for transferring parameters using a href tag without causing a page refresh

Is there a way to pass parameter values without refreshing the page? I would appreciate any help. Thank you. searchresult.php <a href="index.php?id=<?php echo $data['ID']?>">clickme</a> index.php <?php echo $_GET['id ...

Struggling with React integration of AdminLTE3 sidebar treeview?

I have a requirement to create a React sidebar with a category 'Staff' that, when clicked, reveals three subordinate categories. Below is the code snippet: import React, { Component } from "react"; export default class Sidebar extends Componen ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

Class methods cannot be invoked within their constructor

I'm currently facing challenges with implementing my express router. This is a "subrouter" of my main router, hence I need to extend express.Router. Here's an example of the code (simplified to include only one method): import express from "expr ...

When the onclick event is triggered, the return value will execute after the onclient

After my onclientclick event finishes, I am trying to run my onclick event. However, regardless of whether my checkbox is selected or not, the program keeps prompting me to "Please select at least one to delete." Can anyone help me figure out why this is h ...