samedi 15 juillet 2023

JQuery Deselect Checkbox once greater than max limit

So we have a group of checkboxes. There is a max limit of 3 that can be selected which is great. This is for a product designer I am working on so I can make custom orders for people. I have noticed when testing that people get frustrated when they want to go and click another checkbox but since the three have been picked they have to go back and uncheck a checkbox before making another selection. Its not the biggest deal but I would like for that flow to not be broken.

Here is a quick example of some checkboxes and a jquery max limit.

$('input[type=checkbox]').change(function(e) {
  if ($('input[type=checkbox]:checked').length > 3) {
    $(this).prop('checked', false)
    alert("allowed only 3");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="pricing-levels-3">
  <p><strong>(Select 3 Checkboxes)</strong></p>
  <input class="single-checkbox" type="checkbox">1<br>
  <input class="single-checkbox" type="checkbox">2<br>
  <input class="single-checkbox" type="checkbox">3<br>
  <input class="single-checkbox" type="checkbox">4<br>
  <input class="single-checkbox" type="checkbox">5<br>
</div>

Would I need to make an array that logs each chosen checkbox so when we go over our max, say over three into the fourth choice it unchecks the checkbox at the bottom of the array and then unloads it before loading the next one in?

In some other words, I sort of want this to work like a radio button but with the advantages of checkboxes where the user can check and uncheck multiple options but if they go over it just unloads one of their previous choices.

Any suggestions or examples would be greatly appreciated. I have only been able to find examples of limiting the amount of checkboxes that can be selected. Nothing for this particular case.




Aucun commentaire:

Enregistrer un commentaire