mercredi 20 janvier 2016

jquery switchery need to limit the number of selected switches

I have a page with multiple checkboxes for selecting various options, and the user is allowed to select up to 6 options only.

I had this fully working with standard html checkboxes fine, using the following code:

$('.checkbox').on('click', function(e) {
var num_checked = 0;
$('.checkbox').each(function() { if ($(this).prop('checked')) { num_checked++; } });
if (num_checked > 6) { $(this).prop('checked', false); }
});

I have since added the jquery switchery library, to turn the checkboxes into iOS style switches.

I set this up using the code:

var elems = Array.prototype.slice.call(document.querySelectorAll('.ios-switch'));
elems.forEach(function(html) {
var switchery = new Switchery(html, { size: 'small' });
});

Which works fine for styling all the checkboxes on the page, but now the first bit of code that limits the number of selections no longer works.

I have tried various snippets of code and methods from the switchery site, but I am unable to get back the functionality I had at the start, whereby the user is only allowed to select a maximum of 6 options.




Aucun commentaire:

Enregistrer un commentaire