How to use Javascript to limit the number of checkboxes that can be selected?

0

Hello, I'm doing a mini-project on jsfidlle, follow the link link There are several buttons and the user will have to select one of them, as shown below:

When the user chooses how many numbers he wants to bet, the table with the numbers appears. The problem is that my function below is not working (I set the limit of 6 as an example, the correct one would be the limit if it adjusted according to the option selected by the user. follows the function code:

(function($){

var currentLimit=6;

$('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();
    }
});
})

Another thing I think would be more practical would be to replace checkboxes with some kind of button.

    
asked by anonymous 22.02.2016 / 16:09

2 answers

0

First thing you should do, replace and with " , this is interfering with your HTML, so make your inline events get the event parameter as an argument. >

Second point, in method myFunction store the threshold quantity of inputs in a variable.

<button data-value="6" class='btn btn-info custom'onclick="myFunction(event)">6 (R$ 2,00)</button>

var limite = 0;
function myFunction(event) {
  var x = document.getElementById("tabela");
  x.style.display = "inline-block";
  limite = parseInt(event.target.dataset.value);
}

Finally, implement the KeepCount method ...

var quantidade = 0;
function KeepCount(event) {
    if (event.target.checked && quantidade == limite) {
        event.preventDefault();
        return;
    }
    quantidade += event.target.checked ? 1 : -1;    
}

Follow your updated fiddle: JSFiddle

    
22.02.2016 / 16:54
0

See these two examples:

$(document).on('change', '.shared', function() {
  var countShared = $('.shared:checked').length;
  if (countShared > 3 && $(this).is(':checked')) {
    alert("You have reached the maximum number of selectable checkboxes.");
    $(this).prop('checked', false);
  }
});

DEMO Link

or

$(document).on('change', '.shared', function() {
    var countShared = $('.shared:checked').length;
    if(countShared > 3) {          //<-------------here is the difference
        alert("You have reached the maximum number of selectable checkboxes.");
        $(this).prop('checked',false);
    }
});

DEMO Link

Additional:

Example with Jquery

I hope I have helped;

Source: link

    
22.02.2016 / 16:38